我在下面编写了一些代码,目前我正在测试,因此代码中没有数据库查询。
下面的代码说的是if(filesize($filename) != 0)
总是去else
即使文件不是 0 字节并且其中有 16 字节数据。我一无所获,它似乎总是认为文件是 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
}
基本上,代码将位于会员列表页面上,该页面当前检索所有会员并计算注册的会员数量。脚本中的要点是,如果时间少于 24 小时,我们从文件中读取member_count,否则如果已经过了 24 小时或更长时间,则我们查询数据库,获取成员计数并将新数字写入文件,这是为了减少对会员列表页面。
更新1:
这段代码:
echo "The file size is actually ".filesize($filename)." bytes.\n";
始终输出以下内容,即使它不是 0 字节。
文件大小实际上是0字节。
也尝试过
var_dump (filesize($filename));
Outputs:
int(0)
您正在使用:
fopen($filename, "w+")
根据说明书w+
means:
开放阅读和写作;将文件指针放在文件的开头并将文件截断为零长度。如果该文件不存在,请尝试创建它。
所以文件大小为 0 是正确的。
你可能需要r+
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)