脚本宝典收集整理的这篇文章主要介绍了如何在不覆盖现有文件的情况下在PHP中复制文件?,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
拨打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,请注明来意。