我有这个:
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$mystring = $_SERVER['REMOTE_ADDR']; //IP according to server
$findme = file_get_contents($fi2);
$pos = strpos($mystring, $findme);
if ($pos === true) {
echo "Found";
} else {
echo "not found";
}
但是,即使 IP 与文本文件中的某些内容匹配,它也不会说“未找到”。我已经做到了
echo "$mystring $findme";
它正确输出我的 IP 和文本文件。
有人告诉我应该更换
if ($pos === true) {
与
if ($pos !== false) {
我已经这样做了,但仍然不起作用。
这是我用来保存到文本文件的代码:
//Record IP
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
我认为这是三个问题的结合。
首先,如果您正在加载的文件的 IP 地址末尾有一个新行,则它将不匹配:
$findme = file_get_contents($fi2);
更改为
$findme = trim(file_get_contents($fi2));
也正如其他人指出的那样,你的 pos 逻辑是不正确的。
if ($pos !== false) {
编辑:
你的 strpos 参数顺序也是错误的:
$pos = strpos($findme, $mystring);
strpos()
:
返回针相对于 haystack 字符串开头的位置(与偏移量无关)。另请注意,字符串位置从 0 开始,而不是 1。
如果未找到针,则返回
。
FALSE
所以结果是一个数字位置或
FALSE
,这意味着$pos === true
always失败!另一个问题是strpos()
的签名如下:
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
您混淆了
$haystack
和$needle
,这可能是由于命名不当造成的。尝试这样的事情:
$fi2 = "/var/www/server/poll/ips.txt"; //IP file
$ip = $_SERVER['REMOTE_ADDR']; //IP according to server
$file = file_get_contents($fi2);
$pos = strpos($file, $ip);// ($findme, $mystring)
if ($pos !== FALSE) {
echo "found";
} else {
echo "not found";
}
strpos
返回一个数字,如果未找到则返回 false
。
正确的 if 语句是:
if ($pos !== false) {
另一个常见错误是这样写:
if (!$pos) {
但是如果
$pos
是 0
- 如果在字符串的开头找到该字符串,则会发生这种情况 - 此检查也会失败。
if 语句的替代方案:
if(!is_bool($pos)){
我自己才弄清楚。
我变了
file_put_contents($fi2, "\r\n$mystring", FILE_APPEND); //Stick it onto the IP file
至
file_put_contents($fi2, "$mystring", FILE_APPEND); //Stick it onto the IP file
我不知道为什么会修复它(刚刚启动 PHP),但这就是它被破坏的原因,所以如果有人提出用原始行修复它的答案,我会接受它。
还需要将
$pos === true
更改为 $pos !== false
。