当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何在不覆盖现有文件的情况下在PHP中复制文件?》经验,为你挑选了1个好方法。

当您使用PHP 复制功能时,操作会盲目地复制目标文件,即使它已经存在.如何安全地复制文件,如果没有现有文件,只执行复制?



1> Douglas Mayl..:

显而易见的解决方案是调用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;
}

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有