Search code examples
phpfopenfwritephp-7fread

PHP save to file script giving errors after upgrade to PHP 7.0


I have rather simple script that is supposed to add new line of string to a file.

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

After upgrading to PHP 7.0 I get errors:

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

Could anyone explain why this error shows up and how it can be fixed? What is it with PHP 7.0 that caused it suddenly to stop working?


Solution

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

    Or you can try to use The SplFileObject class - an object oriented interface for a file.