php不覆盖原先的文本,如何在不覆盖现有文件的情况下在PHP中复制文件?

本文介绍了一种使用fopen函数以创建模式'x'来确保在复制文件时不覆盖已存在文件的方法。通过这种方式,可以避免在调用file_exists和copy之间的竞争条件。如果文件已存在,fopen会失败,从而可以防止不必要的覆盖。提供的示例代码展示了如何实现这个安全的文件复制过程。
摘要由CSDN通过智能技术生成

显而易见的解决方案是调用

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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值