如何在不覆盖现有文件的情况下在PHP中复制文件?

时间:2008-10-22 18:00:53

标签: php file file-io

当您使用PHP copy函数时,操作会盲目地复制目标文件,即使它已经存在。如何安全地复制文件,如果没有现有文件则仅执行复制?

4 个答案:

答案 0 :(得分:8)

显而易见的解决方案是调用file_exists来检查文件是否存在,但这样做可能会导致竞争条件。当您致电file_exists和致电copy时,总有可能在其间创建其他档案。检查文件是否存在的唯一安全方法是使用fopen

当您致电fopen时,请将模式设为“x”。这告诉fopen创建文件,但前提是它不存在。如果存在,fopen将失败,您将知道无法创建该文件。如果成功,您将在目的地创建一个可以安全复制的文件。示例代码如下:

// The PHP copy function blindly copies over existing files.  We don't wish
// this to happen, so we have to perform the copy a bit differently.  The
// only safe way to ensure we don't overwrite an existing file is to call
// fopen in create-only mode (mode 'x').  If it succeeds, the file did not
// exist before, and we've successfully created it, meaning we own the
// file.  After that, we can safely copy over our own file.

$filename = 'sourcefile.txt'
$copyname = 'sourcefile_copy.txt'
if ($file = @fopen($copyname, 'x')) {
    // We've successfully created a file, so it's ours.  We'll close
    // our handle.
    if (!@fclose($file)) {
        // There was some problem with our file handle.
        return false;
    }

    // Now we copy over the file we created.
    if (!@copy($filename, $copyname)) {
        // The copy failed, even though we own the file, so we'll clean
        // up by itrying to remove the file and report failure.
        unlink($copyname);
        return false;
    }

    return true;
}

答案 1 :(得分:3)

我认为您已回答了自己的问题 - 请在执行复制之前检查目标文件是否存在。如果文件存在,请跳过副本。

更新:我发现你确实回答了自己的问题。你提到竞争条件,但如果你发现文件已经存在,你怎么知道:

  • 已存在的文件确实是您要复制的文件
  • 复制文件的其他进程已完成其工作(文件数据全部存在)
  • 复制文件的其他进程不会失败(并保留不完整的文件或删除新文件)

我认为在设计问题解决方案时应该考虑这些问题。

答案 2 :(得分:0)

尝试使用link()功能代替copy()

function safe_copy($src, $dest) {
    if (link($src, $dest)) {
        // Link succeeded, remove old name
        unlink($filename);
        return true;
    } else {
        // Link failed; filesystem has not been altered
        return false;
    }
}

不幸的是,这将在Windows上运行。

答案 3 :(得分:0)

蜂蜜獾功能,它不关心竞争条件,但跨平台工作。

function safeCopy($src, $dest) {
    if (is_file($dest) === true) {
        // if the destination file already exists, it will NOT be overwritten.        
        return false;
    }

    if (copy($src, $dest) === false) {
        echo "Failed to copy $src... Permissions correct?\n";
        return false;
    }

    return true;   
}