当您使用PHP的copy函数时,该操作会盲目地复制目标文件,即使它已经存在。如果要安全地复制文件,只有在没有现有文件的情况下才执行复制操作,应该如何处理?
当您调用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;
}
function safeCopy($src, $dest) {
if (is_file($dest) === true) {
// if the destination file already exists, it will NOT be overwritten.
return false;
}
if (copy($src, $dest) === false) {
echo "Failed to copy $src... Permissions correct?\n";
return false;
}
return true;
}
尝试使用link()
函数代替copy()
。
function safe_copy($src, $dest) {
if (link($src, $dest)) {
// Link succeeded, remove old name
unlink($filename);
return true;
} else {
// Link failed; filesystem has not been altered
return false;
}
}
很遗憾,这在Windows上不会起作用。