R_Marlatt
R_Marlatt

Reputation: 119

PHP in_array() not working

I have a security token that is created when a page loads and writes that token to a file. Then I confirm that the token passed in the form matches one of the tokens in the file.

This first section is located in the FORM.PHP file, and I can confirm that the token is being written to the file.

//Create Token
$token = md5(time());

//Save token to file
$fp = fopen('/PATH/tokens.txt', 'a') or die ("Unable to open to Token file");
fwrite($fp, "$token\n") or die ("Unable to write to Token file");
fclose($fp);

This section of code is located in the PROCESS.PHP file. I have printed out the contents of the $tokens array and I can manually confirm that the same token is in there.

$tokens = file('/PATH/tokens.txt') or die("Unable to read file");

$token = $_POST['token'];

if (in_array($token, $tokens)){
   error_log("Found Token");
} else {
   error_log("Token Not Found");
}

I can't figure out why the in_array($token, $tokens) function is not returning TRUE.

Upvotes: 1

Views: 160

Answers (3)

Loopo
Loopo

Reputation: 2195

the file function will return an array with the newlines attached

Upvotes: 0

bjori
bjori

Reputation: 2104

file() keeps the newlines character by default, which means you are matching a md5() to md5()\n.

To strip the newline character out, you need to pass FILE_IGNORE_NEW_LINES as a second argument to file()

Upvotes: 2

Wrikken
Wrikken

Reputation: 70540

Use file('/path/file.ext',FILE_IGNORE_NEW_LINES);, otherwise every entry has the newline characters from the file appended.

Upvotes: 2

Related Questions