如何解决PHP file_get_contents 读取本地文件有时会给我空字符串,但应该总是有一些东西在里面
我的 centos cron-job 代码读取本地文件,有时会得到一个空字符串,但我从不向该文件写入空字符串。
/*
* in a cron job
*/
// verify that the file exists
if (!file_exists($my_file_path)) // if the file does Not exist
{ // then error
error_log("file does Not exist");
exit();
}
// read the file contents
$file_contents = file_get_contents($my_file_path);
// check result
if ($file_contents === false) // if read Failed
{ // then error
error_log("file_contents === false");
exit();
}
// look for empty string
if ($file_contents === '') // if contents is empty string
{ // then check again after sleep
error_log("file_contents === ''");
sleep(1);
$file_contents = file_get_contents($my_file_path);
if ($file_contents === false) // if read Failed
{ // then error
error_log("file_contents === false,after sleep");
exit();
}
if ($file_contents === '') // if contents is still empty
{ // then log it and exit
error_log("file_contents is still empty,after sleep");
exit();
}
else // else contents Now Exists
{ // so log it and use contents
error_log("file_contents Exists,after sleep: $file_contents");
}
}
我在两个地方写入文件:
// write the file contents
file_put_contents($my_file_path,time());
在一个地方我可以删除文件(但我检查过了,这段代码没有被执行):
// remove the file
unlink($my_file_path);
我不明白 file_get_contents 应该如何给我一个空字符串,即使它被取消链接。
解决方法
尝试使用文件的完整路径 /var/www/html/.... /your_doc.php
这可以帮助您
NVRM 得到了答案。我在 file_put_contents() 操作和 file_get_contents() 操作之间存在竞争条件。我不知道 file_put_contents() 不是原子操作,即使它是“写入”而不是“追加”。
我可以通过多种方式修复我的代码。这是 2:
- 使用羊群
- 写入临时文件,然后使用重命名(因为重命名是 ataomic)
我的是一个特殊的、非常简单的案例,我只需要在我的网页脚本和一个定时任务之间共享一个时间戳。所以我放弃了 file_put_contents() 和 file_get_contents() 的使用,并用 touch() 和 filemtime() 替换了该代码。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。