PHP - 仅在文件不存在时复制

PHP - Copy ONLY if the file does not exist

我已经阅读了数十个类似的问题,但 none 的答案正是我所需要的。如果它存在,请指出它。

我有一个名为 "txts" 的文件夹和另一个名为 "content" 的文件夹,如下所示:

files/texts    files/content

我想将文件从 "txts" 复制到 "contents",但前提是 "content" 文件夹中不存在该文件。

这是我使用的代码:

<?php 
 copy('files/txts/file1.txt', 'files/content/file1.txt');
?>

问题是如果它已经存在就会被覆盖。我需要复制文件(不删除原始文件)并将其添加到目标文件夹(如果它不存在)。

您正在寻找file_exists()

if(!file_exists('files/content/file1.txt')){
    copy('files/txts/file1.txt', 'files/content/file1.txt');
}else{
    echo "file already exists";
}

使用file_exists()函数。 http://php.net/manual/en/function.file-exists.php

if (!file_exists($dest_loc)){
    copy($source_loc, $desk_loc);
}