开发者

Strange Boolean Reaction

开发者 https://www.devze.com 2023-02-17 11:05 出处:网络
$alerter2=\"false\"; for ( $counter = 0; $counter <= count($filter); $counter++) { $questionsubmitted=strtolower($_POST[question]);
$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
    $questionsubmitted=strtolower($_POST[question]);
    $currentcheck =$filter[$counter];
    $foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
    echo $foundvalue;
    if ($foundvalue==0) {
        $alerter2="true";
    } else { }
}

if (!($alerter2=="true")) {
    $sql="INSERT INTO Persons (Name, Email, Q开发者_如何学运维uestion)
        VALUES
        ('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
    echo "Please only post appropriate questions";
}

For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.

Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.


stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.

You can use === to also check the type of the variable :

if ($foundvalue === 0) {
    $alerter2="true";
}

There's more details about this problem in the linked documentation for stripos.

You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.


You need to change

if ($foundvalue==0)

to

if ($foundvalue===0) // three equals signs

or something equivalent, depending on your logic (I didn't quite understand what's going on).

But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).


Also,

$questionsubmitted=strtolower($_POST[question]);

should probably be:

$questionsubmitted=strtolower($_POST['question']);
0

精彩评论

暂无评论...
验证码 换一张
取 消