PHP strcmp
The strcmp()
function in PHP is used to compare two strings in a binary-safe manner. If strings are:
identical → returns
0
first string > second string → positive number
first string < second string → negative number
When improperly implemented in authentication logic, this function can be abused due to PHP’s type juggling behavior which refers to the automatic conversion that PHP performs when comparing values of different types. Instead of strictly enforcing type equality, PHP tries to convert one or both values to a common type before making the comparison.
This behavior can lead to unexpected results, especially when loose comparison operators like ==
are used. For example, when comparing NULL
and 0
with ==
, PHP treats them as equal because both are considered "empty" or "falsey" values after type conversion. This implicit conversion can create vulnerabilities if a developer assumes strict type checks without using strict comparison operators (===
), potentially allowing attackers to bypass security checks by exploiting these type coercions.
As a result, supplying an empty array as an argument causes strcmp()
to return NULL
, and in loose comparisons, NULL == 0
evaluates to true. If the developer checks the strcmp()
return value using a loose comparison against 0
, the authentication condition may pass even when the provided input is not the correct password.
In the below scenario, sending $_POST['password']
as an empty array (password[]=""
) results in strcmp()
returning NULL
, which in a loose comparison is treated as equal to 0
. This allows bypassing the password check entirely and gaining unauthorized access.
if($_GET['login'] === "1"){
if (strcmp($_POST['username'], "admin") == 0 && strcmp($_POST['password'], $pass) == 0) {
echo "Welcome! </br> Go to the <a href=\"dashboard.php\">dashboard</a>";
}
}
Last updated
Was this helpful?