PHP保存到文件脚本,在升级到PHP 7.0后出错

Gre*_*Viv 0 php fopen fwrite fread php-7

我有一个相当简单的脚本,应该在文件中添加新的字符串.

if (isset($_POST["score"]))
{
$myFile = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);

$File = $_SERVER['DOCUMENT_ROOT']."/xx/zz.txt"; 
$Handle = fopen($File, 'w');
$Data = $_POST["score"]."\n".$theData; 
fwrite($Handle, $Data); 
fclose($Handle); 
}
Run Code Online (Sandbox Code Playgroud)

升级到PHP 7.0后,我收到错误:

fread() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 7
fclose() expects parameter 1 to be resource, boolean given in /home/zzz/public_html/zzz.php on line 8
Run Code Online (Sandbox Code Playgroud)

谁能解释为什么会出现这个错误以及如何修复它?什么是PHP 7.0导致它突然停止工作?

小智 5

//First, see if the file exists
if (!is_file($myFile))
{
    die("<b>404 File not found!</b>");
}
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试使用SplFileObject类 - 文件的面向对象的接口.