我在下面编写了一些代码,目前我正在测试,所以代码中没有数据库查询.
即使文件不是0字节并且其中有16个字节的数据,下面的代码if(filesize($filename) != 0)总是会else出现.我无处可去,似乎总是认为文件是0字节.
我认为显示我的代码更容易(可能是其他错误,但我正在检查每个错误,我一个接一个地处理它们).我没有PHP错误或任何东西.
$filename = 'memberlist.txt';
$file_directory = dirname($filename);
$fopen = fopen($filename, 'w+');
// check is file exists and is writable
if(file_exists($filename) && is_writable($file_directory)){
// clear statcache else filesize could be incorrect
clearstatcache();
// for testing, shows 0 bytes even though file is 16 bytes
// file has inside without quotes: '1487071595 ; 582'
echo "The file size is actually ".filesize($filename)." bytes.\n";
// check if file contains any data, also tried !==
// always goes to else even though not 0 bytes in size
if(filesize($filename) != 0){
// read file into an array
$fread = file($filename);
// get current time
$current_time = time();
foreach($fread as $read){
$var = explode(';', $read);
$oldtime = $var[0];
$member_count = $var[1];
}
if($current_time - $oldtime >= 86400){
// 24 hours or more so we query db and write new member count to file
echo 'more than 24 hours has passed'; // for testing
} else {
// less than 24 hours so don't query db just read member count from file
echo 'less than 24 hours has passed'; // for testing
}
} else { // WE ALWAYS END UP HERE
// else file is empty so we add data
$current_time = time().' ; ';
$member_count = 582; // this value will come from a database
fwrite($fopen, $current_time.$member_count);
fclose($fopen);
//echo "The file is empty so write new data to file. File size is actually ".filesize($filename)." bytes.\n";
}
} else {
// file either does not exist or cant be written to
echo 'file does not exist or is not writeable'; // for testing
}
Run Code Online (Sandbox Code Playgroud)
基本上,代码将位于成员列表页面上,该页面当前检索所有成员并计算注册的成员数量.脚本中的一点是如果时间少于24小时我们从文件中读取member_count,如果已经过了24小时或更长时间,那么我们查询数据库,获取成员计数并将新数字写入文件,这是为了减少查询成员列表页面.
更新1:
这段代码:
echo "The file size is actually ".filesize($filename)." bytes.\n";
总是输出以下,即使它不是0字节.
文件大小实际上是0字节.
也试过了
var_dump (filesize($filename));
输出:
INT(0)
您正在使用:
fopen($filename, "w+")
Run Code Online (Sandbox Code Playgroud)
根据手册的w+意思:
开放阅读和写作; 将文件指针放在文件的开头,并将文件截断为零长度.如果该文件不存在,请尝试创建它.
所以文件大小为0是正确的.
你可能需要 r+