微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PHP file_get_contents 读取本地文件有时会给我空字符串,但应该总是有一些东西在里面

如何解决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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?