【问题标题】:Php fopen erros when file exists already当文件已经存在时,php fopen 错误
【发布时间】:2014-12-09 19:28:14
【问题描述】:

我有以下脚本来编写我从网上抓取的文件。

$newfname = $data['transferPath'] . '/' . $data['filename'];
$file = fopen ($data['filePath'], "rb");

if(!$file) {
    throw new Exception('Unable to open file for reading ' . $file);
}

if($file) {
    $newf = fopen ($newfname, "wb");

    if(!$newf) {
        throw new Exception("Cant open file for writing");
    }

    if($newf) {
        while(!feof($file)) {
            fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
        }
    }
}

if($file) {
    fclose($file);
}

if($newf) {
    fclose($newf);
}

当我发布数据并运行此脚本时,我不断收到无法打开文件进行写入的异常,因为已经有一个文件但该名称位于同一目录中。我试图用新文件覆盖文件任何想法我能做什么。 iv 尝试使用 w 和 w+ 的 fopen 选项。如果存在,我需要完全覆盖那里的文件,否则创建文件。

【问题讨论】:

  • 请打开错误报告,如果你还没有这样做,还有,你有那个文件的写权限吗?

标签: php file-upload fopen


【解决方案1】:

尝试在fopen() 函数中使用a+ 结束参数。

查看here 以获取可能参数的完整列表以及它们如何为您的目的找到合适的参数!

如果这些都不能满足您的需求,那么您可以这样做:

$fopen($data['filePath'], "r");
if($file){
    unlink($data['filePath']);
}

然后在它删除文件之后,如果它在那里,那么只需使用w 参数执行另一个fopen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-17
    • 2014-06-29
    • 2023-03-07
    • 2021-05-08
    • 1970-01-01
    • 2021-10-04
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多