PHP fopen, fwrite and fclose proceed without errors but no file created

时间:2018-03-25 18:53:43

标签: php linux lamp

I am running PHP 7.0.22, under LAMP, on two ubuntu 16.04.

The following code proceeds without throwing an exception and $tempFile has the value Resource id #4.

    try {
            // Open temp file for writing
            $tempFile = fopen("/var/www/dropbox/temp.lst", "w");

            echo "tempfile=" . $tempFile .  "<br>";

            // Write list of file names to file
            for ($x = 0; $x <= $inputFileCount; $x++) {
                    fwrite($tempFile, $fileNames);
            }

            // Close temp file
            fclose($tempFile);
    } catch ( Exception $e ) {
            // send error message if you can
            echo 'Caught exception: ',  $e->getMessage(), "\n";
    }

However, no file, by the name of temp.lst, appears in the directory /var/www/dropbox/ which has full write permission.

ls -ld /var/www/dropbox/
drwxrwsrwx 2 ubuntu www 4096 Mar 25 18:13 /var/www/dropbox/

No errors, related to the code, are shown by

cat /var/log/apache2/error.log

1 个答案:

答案 0 :(得分:2)

fopen, fwrite, fclose don't throw Exceptions, they return errors

Try

try {
        // Open temp file for writing
        $tempFile = fopen("/var/www/dropbox/temp.lst", "w");
        if (false === $tempFile) throw new \RuntimeException("Failed to open file");

        echo "tempfile=" . $tempFile .  "<br>";

        // Write list of file names to file
        for ($x = 0; $x <= $inputFileCount; $x++) {
                if(false === fwrite($tempFile, $fileNames)) throw new \RuntimeException("Failed to write to file"); 
        }

        // Close temp file
        if(false === fclose($tempFile)) throw new \RuntimeException("Failed to close file"); 
} catch ( Exception $e ) {
        // send error message if you can
        echo 'Caught exception: ',  $e->getMessage(), "\n";
}

and you should get some exceptions