我正在尝试搜索文件,如果已经有in_array的ip。但是我得到了这个错误
Warning: in_array() expects parameter 2 to be array, resource given in
。
var $RATES_RESULT_FILE = "results.txt";
function writeResult($item,$rate){
$ip = getenv('REMOTE_ADDR'); // ip looks like an usual ip 127.0.0.1..
$f = fopen($this->RATES_RESULT_FILE,"a+");
if(!in_array($ip, $f)) {
if ($f != null) {
fwrite($f,$item.':::'.$ip.':::'.$rate."\n");
fclose($f);
}
}
}
fwrite
用英文看起来像这样:$ f,String ::: 127.0.0.1 ::: 5(规模1-5票)
它将文件识别为资源而不是数组,无论如何都要将文件从资源转换为数组。 最终的results.txt文件看起来像这样:
String:::41.68.178.78:::3
String:::41.68.178.78:::2
String:::41.68.178.78:::1
String:::175.68.178.78:::5
答案 0 :(得分:1)
扩展Doge的答案,首先需要构建数组。这可以使用array_map
给出的数组上的file
来解析IP地址。但是,这样做可能更容易:
$contents = file_get_contents($this->RATES_RESULT_FILE);
if( strpos($contents,$ip) === false) {
$contents .= $item.":::".$ip.":::".$rate."\n";
file_put_contents($this->RATES_RESULT_FILE, $contents);
}
但是,这可能会占用大量内存,尤其是在文件变大的情况下。对内存更友好的方式是:
exec("grep -F ".escapeshellarg($ip)." ".escapeshellarg($this->RATES_RESULT_FILE),
$_, $exitcode);
// I use $_ to indicate a variable we're not interested in
if( $exitcode == 1) { // grep fails - means there was no match
// or use $exitcode > 0 to allow for error conditions like file not found
$handle = fopen($this->RATES_RESULT_FILE,"ab");
fputs($handle, $item.":::".$ip.":::".$rate."\n");
fclose($handle);
}
编辑:exec
- 替换fopen/fputs/fclose
:
exec("echo ".escapeshellarg($item.":::".$ip.":::".$rate."\n")." >> "
.escapeshellarg($this->RATES_RESULT_FILE));
答案 1 :(得分:0)
$f = fopen($this->RATES_RESULT_FILE,"a+");
if(!in_array($ip, $f)) {
$f
是文件资源而不是数组。
您是否打算改为file
?
$f = file($this->RATES_RESULT_FILE);
if(!in_array($ip, $f)) {