简体   繁体   English

PHP in_array()不起作用

[英]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. 第一部分位于FORM.PHP文件中,我可以确认该令牌正在写入该文件。

//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. 这部分代码位于PROCESS.PHP文件中。 I have printed out the contents of the $tokens array and I can manually confirm that the same token is in there. 我打印出$ tokens数组的内容,我可以手动确认那里有相同的令牌。

$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. 我无法弄清楚为什么in_array($token, $tokens)函数没有返回TRUE。

Use file('/path/file.ext',FILE_IGNORE_NEW_LINES); 使用file('/path/file.ext',FILE_IGNORE_NEW_LINES); , otherwise every entry has the newline characters from the file appended. ,否则每个条目都附加了文件中的换行符。

file() keeps the newlines character by default, which means you are matching a md5() to md5()\\n. file()默认保留换行符,这意味着您将md5()与md5()\\ n匹配。

To strip the newline character out, you need to pass FILE_IGNORE_NEW_LINES as a second argument to file() 要删除换行符,需要将FILE_IGNORE_NEW_LINES作为第二个参数传递给file()

文件函数将返回附加了换行符的数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM