【发布时间】:2017-02-14 12:06:31
【问题描述】:
我在下面写了一些代码,目前我正在测试,所以代码中没有数据库查询。
下面的代码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));
输出:
int(0)
【问题讨论】:
-
你检查
var_dump (filesize($filename));了吗?给我们看 -
@Anant 我得到:int(0) 干杯。
-
@apokryfos 我的脚本中没有该代码,不确定您的意思,整个脚本都在上面。更新帖子以提供更多信息。干杯。