Link to home
Start Free TrialLog in
Avatar of cgray1223
cgray1223

asked on

how to not overwrite image using php copy command

Hello,
I'm using the below snippet of php to copy a file from one directory to another, but if the $file already exists in the $upload_directory_to it just overwrites it.  I would rather it keep the original and rename it filename(1) or something like that.  The reason being that I'm inserting a record in my DB each time as even though the $file has the same name, it may be a different file.  Any recommendations?
if (!copy($upload_directory_from.$file, $upload_directory_to.$file)) {
    echo "failed to copy $file...\n";
}

Open in new window

Avatar of Snarfles
Snarfles
Flag of Australia image

Try this
if (file_exists($upload_directory_to.$file)) {
    $file = $file."2";
//or rename it however you like in this section
}

Open in new window

Hmm for your filename we need to put it before the extension...
if (file_exists($upload_directory_to.$file)) {

$info = pathinfo($file);
$file_name =  basename($file,'.'.$info['extension']);
$file = $file_name."_2".$info['extension'];
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial