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

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

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

当前回答

嗯…根据这份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建议的那样做。

其他回答

Strcmp()和===都是区分大小写的,但是===更快。

示例代码:Speed Test: strcmp vs ===

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

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

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

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

嗯…根据这份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建议的那样做。

不要在PHP中使用==。它不会如你所愿。即使是字符串与字符串进行比较,PHP也会隐式地将它们转换为浮点数,并在它们显示为数值时进行数值比较。

例如,'1e3' == '1000'返回true。您应该使用===代替。