PHP的===操作符似乎是区分大小写的。那么,是否有理由使用strcmp()呢?

做下面这样的事情安全吗?

if ($password === $password2) { ... }

当前回答

strcmp将根据其运行的环境(Linux/Windows)返回不同的值!

原因是它有一个错误,正如错误报告所说- bug #53999strcmp()并不总是返回-1、0或1

其他回答

strcmp将根据其运行的环境(Linux/Windows)返回不同的值!

原因是它有一个错误,正如错误报告所说- bug #53999strcmp()并不总是返回-1、0或1

嗯…根据这份PHP bug报告,你甚至会被骗。

<?php
    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
    // Query /?pass[]= will authorize user
    //strcmp and strcasecmp both are prone to this hack
    if ( strcasecmp( $pass, '123456' ) == 0 ){
      echo 'You successfully logged in.';
    }
 ?>

它给了你一个警告,但仍然绕过了比较。 你应该像@postfuturist建议的那样做。

始终记住,在比较字符串时,应该使用===操作符(严格比较)而不是==操作符(松散比较)。

此外,该函数可以帮助排序。为了更清楚地理解排序。如果string1在string2之前排序,Strcmp()返回小于0;如果string2在string1之前排序,则返回大于0;如果两者相同,则返回0。例如

$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string, $second_string);

函数将返回大于零的值,因为aaao在aabo之前排序。

永远不要使用==进行字符串比较。===是可以的。

$something = 0;
echo ('password123' == $something) ? 'true' : 'false';

只要运行上面的代码,你就会明白为什么。

$something = 0;
echo ('password123' === $something) ? 'true' : 'false';

现在好一点了。