首页 > 解决方案 > 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 应该如何给我一个空字符串,即使它被取消链接。

标签: phplinuxfilefile-get-contents

解决方案


尝试使用文件的完整路径,/var/www/html/.... /your_doc.php这可以帮助您


推荐阅读