PHP   发布时间:2019-11-21  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在不覆盖现有文件的情况下在PHP中复制文件?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
您使用 PHP copy函数时,操作将盲目地复制目标文件,即使它已经存在.如何安全地复制文件,如果没有现有文件,只执行复制?

解决方法

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

大佬总结

以上是大佬教程为你收集整理的如何在不覆盖现有文件的情况下在PHP中复制文件?全部内容,希望文章能够帮你解决如何在不覆盖现有文件的情况下在PHP中复制文件?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。