如何在不复制现有文件的情况下在PHP中复制文件? [英] How do you copy a file in PHP without overwriting an existing file?

查看:231
本文介绍了如何在不复制现有文件的情况下在PHP中复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用PHP 复制功能时,操作会盲目复制在目标文件上,即使它已经存在。如何安全地复制文件,只有在没有现有文件的情况下才执行复制? 解决方案

显而易见的解决方案是请致电 file_exists 检查文件是否存在,但这样做可能会导致竞争状况。当你调用 file_exists ,当你打电话复制。检查文件是否存在的唯一安全方法是使用 fopen



当调用 fopen ,将模式设置为x。这告诉的fopen 创建的文件,但只有当它不不存在。如果存在, fopen 将会失败,你会知道您无法创建该文件。如果成功,您将在目的地创建一个文件,您可以安全地复制。示例代码如下:

  // PHP复制函数会盲目复制现有文件。我们不希望
//发生这种情况,所以我们必须以不同的方式执行复制。
// //确保我们不覆盖现有文件的唯一安全方法是在仅创建模式(模式x)中调用
// fopen。如果成功,文件不存在
//,我们已经成功创建了它,这意味着我们拥有
//文件。之后,我们可以安全地复制我们自己的文件。

$文件名= 'sourcefile.txt'
$ copyname = 'sourcefile_copy.txt'
如果($文件= @fopen($ copyname, 'X')){
//我们已经成功创建了一个文件,所以它是我们的。我们将关闭
//我们的句柄。
if(!@fclose($ file)){
//文件句柄有问题。
返回false;
}

//现在我们复制我们创建的文件。
if(!@copy($ filename,$ copyname)){
//复制失败,即使我们拥有该文件,所以我们将清理
//删除文件并报告失败。
unlink($ copyname);
返回false;
}

return true;
}


When you use the PHP copy function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?

解决方案

The obvious solution would be to call file_exists to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call file_exists and when you call copy. The only safe way to check if the file exists is to use fopen.

When you call fopen, set the mode to 'x'. This tells fopen to create the file, but only if it doesn't exist. If it exists, fopen will fail, and you'll know that you couldn't create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below:

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

这篇关于如何在不复制现有文件的情况下在PHP中复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆