dpyln64620
2018-03-25 18:53
浏览 260
已采纳

PHP fopen,fwrite和fclose没有错误但没有创建文件

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(), "
";
    }

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条回答 默认 最新

  • doukanmang3687 2018-03-25 19:07
    已采纳

    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(), "
    ";
    }
    

    and you should get some exceptions

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题