Craig Edmonds Craig Edmonds - 1 month ago 8
PHP Question

PHP: Detect password parameter in string and replace with default text

I have an api logging system which records logins but I do not want to store passwords in the logs.

This is an example of a request string to the log:

NOTE: the string will not be exactly the same and will contain parameters in different order, so I am thinking maybe someREGEX can handle this?

api.my.geatapim/live/?action=login_user&username=joe@bloggs.com&password=PassWord&session_length=10080


What I need to do, is:


  1. Detect if the parameter "password=" is in the string

  2. If its in the string replace the password part with OBFUSCATED so result will be:



api.my.geatapim/live/?action=login_user&username=joe@bloggs.com&password=OBFUSCATED&session_length=10080

I have tried this but does not work:
$request_string = preg_replace("/password=\d+/", "password=OBFUSCATED", $request_string);

Answer

Try this code, it works

<?php

$request_string = "api.my.geatapim/live/?action=login_user&username=joe@bloggs.com&password=PassWord&session_length=10080";
echo $request_string = preg_replace("/password=\w+/", "password=OBFUSCATED", $request_string);
?>

Output : api.my.geatapim/live/?action=login_user&username=joe@bloggs.com&password=OBFUSCATED&session_length=10080

Comments