PHP如果正在写文件,但“ a +”没有问题,但用“ r”不可读,如何读取文件?

问题描述

我有两个脚本:其中一个将变量的值写入文件。在另一个脚本中,我尝试阅读它。编写时没有问题,但不可读。 在这里我写一个文件

$peer_id=2000000001;
$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
$file = fopen($fileLocation,"a+");
fwrite($file,$peer_id);
fclose($file);

在这里读取文件

$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt"; 
$file = fopen($fileLocation,"r");
if(file_exists($fileLocation)){
        // Result is TRUE
}
if(is_readable ($file)){
      // Result is FALSE
}
// an empty variables,because the file is not readable
$peer_id = fread($file);
$peer_id = fileread($file);
$peer_id = file_get_contents($file);
fclose($file);

代码可以在“ sprinthost”主机上运行,​​如果有区别的话。有人怀疑这是因为托管。

解决方法

file_get_contents简而言之就是fopenfreadfclose。您不使用指针。您应该使用:

$peer_id = file_get_contents($fileLocation);

is_readable相同:

if(is_readable($fileLocation)){
    // Result is FALSE
}

因此完整的代码应类似于:

$fileLocation = getenv("DOCUMENT_ROOT") . "/peer_id.txt";
if(file_exists($fileLocation) && is_readable($fileLocation)) {
     $peer_id = file_get_contents($fileLocation);
} else {
    echo 'Error message about file being inaccessible here';
}

file_get_contents具有反写功能; https://www.php.net/manual/en/function.file-put-contents.php。将其与append常量一起使用,您应该具有与第一个代码块相同的功能:

file_put_contents($fileLocation,$peer_id,FILE_APPEND | LOCK_EX);