KulerGary
KulerGary

Reputation: 217

PHP - Copy ONLY if the file does not exist

I have read dozens of similar questions but none of the answers were what I needed. Please point me to it if it exists.

I have a folder named "txts" and another folder named "content" like this:

files/texts    files/content

I want to copy a file from "txts" to "contents" but only if that file does not already exist in the "content" folder.

Here is the code I am using:

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

The problem is that it gets overwritten if it is already there. I need to copy the file (without deleting the original) and add it to the destination folder if it doesn't already exist.

Upvotes: 2

Views: 5036

Answers (2)

Tanuel Mategi
Tanuel Mategi

Reputation: 1283

you are looking for file_exists():

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

Upvotes: 2

Andrew Coder
Andrew Coder

Reputation: 1058

Use the file_exists() function. http://php.net/manual/en/function.file-exists.php

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

Upvotes: 4

Related Questions