gpt4 book ai didi

php - filesize() 始终读取 0 字节,即使文件大小不是 0 字节

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:43 31 4
gpt4 key购买 nike

我在下面写了一些代码,目前我正在测试,所以代码中没有数据库查询。

下面的代码显示 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
}

基本上,代码将位于成员(member)列表页面上,该页面当前检索所有成员(member)并计算注册成员(member)的数量。脚本中的要点是,如果时间少于 24 小时,我们从文件中读取 member_count,否则如果 24 小时或更长时间过去了,那么我们查询数据库,获取成员计数并将新数字写入文件,这是为了减少对成员(member)列表页面。

更新 1:

这段代码:

echo "文件大小实际上是 ".filesize($filename)."bytes.\n";

总是输出下面的内容,即使它不是 0 字节。

The file size is actually 0 bytes.

也试过

var_dump (filesize($filename));

输出:

int(0)

最佳答案

您正在使用:

fopen($filename, "w+") 

根据手册 w+ 表示:

Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

因此文件大小为 0 是正确的。

你可能需要 r+

关于php - filesize() 始终读取 0 字节,即使文件大小不是 0 字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225750/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com