问题描述
我有两个脚本:其中一个将变量的值写入文件。在另一个脚本中,我尝试阅读它。编写时没有问题,但不可读。 在这里我写一个文件:
$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
简而言之就是fopen
,fread
和fclose
。您不使用指针。您应该使用:
$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);