2017-06-06 49 views
0

我有一个相当简单的脚本,应该将新的字符串添加到文件中。PHP保存到文件脚本升级到PHP 7.0后给出错误

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); 
} 

升级到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 

任何人都可以解释为什么这个错误显示出来,以及如何修复? PHP 7.0是什么让它突然停止工作?

+1

你确定它没有读取以前php版本的旧系统文件吗? 'phpinfo()'显示的是什么,并且该文件最初有内容?如果该文件为空,则会抛出该错误。也检查权限。 –

回答

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

或者你可以尝试使用The SplFileObject class - 一个文件对象接口。

1

fopen()失败时,它返回false。错误不是资源,因此是警告。

你注入它作为一种资源类参数前最好测试$fh

if($fh = fopen($myFile, 'r')) { 

} 
+0

这将意味着fopen无法打开文件$ _SERVER ['DOCUMENT_ROOT']。“/ xx/zz.txt” 但我已检查并发现文件存在。在脚本和FTP文件中都没有改变。为什么升级到PHP 7.0突然导致fopen失败? –

+0

如何检查权限?你可以使用error_log()来确保你的DOCUMENT_ROOT是你相信的。 – Collector