【问题标题】:PHP fopen, fwrite and fclose proceed without errors but no file createdPHP fopen、fwrite 和 fclose 继续没有错误但没有创建文件
【发布时间】:2018-03-25 18:53:43
【问题描述】:

我在两个 ubuntu 16.04 上运行 PHP 7.0.22,在 LAMP 下。

以下代码继续运行,不会引发异常,并且 $tempFile 的值为 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";
    }

但是,名称为 temp.lst 的文件没有出现在具有完全写入权限的目录 /var/www/dropbox/ 中。

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

没有错误,与代码相关,由

显示
cat /var/log/apache2/error.log

【问题讨论】:

  • 请注意:原生 PHP 文件系统函数不会抛出异常。您是否使用自定义错误处理程序?
  • @d3L 偷了我的话,我要补充一点,如果不是,您应该打开错误报告。
  • 谢谢。我打开了错误报告。很有帮助!

标签: php linux lamp


【解决方案1】:

fopen, fwrite, fclose 不要抛出异常,它们会返回错误

试试

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

你应该得到一些例外

【讨论】:

    猜你喜欢
    • 2015-05-24
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-19
    • 1970-01-01
    相关资源
    最近更新 更多