文件存在时Php fopen错误

时间:2014-12-09 19:28:14

标签: php file-upload fopen

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

$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选项。如果存在,我需要完全覆盖那里的文件,否则创建文件。

1 个答案:

答案 0 :(得分:1)

尝试将a+结束参数用于fopen()函数。

查看here以获取可能参数的完整列表,以及他们为找到合适的参数所做的工作!

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

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

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

相关问题