Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a file without overwriting the destination file?

Tags:

file

php

The script I made is.

<?php

$source_file = 'http://www.domain.tld/directory/img.png'; 
$dest_file = '/home/user/public_html/directory/directory/img.png'; 

copy($source_file, $dest_file);

?>

I need that image to not be delete and reuploaded every time the script is running. I would either want it to be img1.png, img2.png, img3.png, etc. Or img(Date,Time).png, img(Date,Time).png, etc. Is this possible and if so, how do I do this?

like image 515
user1861331 Avatar asked Nov 29 '25 22:11

user1861331


1 Answers

If you're concerned with overwriting a file, you could just drop in a timestamp to ensure uniqueness:

$dest_file = '/home/user/public_html/directory/directory/img.png';

// /home/user/public_html/directory/directory/img1354386279.png
$dest_file = preg_replace("/\.[^\.]{3,4}$/i", time() . "$0", $dest_file);

Of if you wanted simpler numbers, you could take a slightly more tasking route and change the destination file name as long as a file with that name already exists:

$file = "http://i.imgur.com/Z92wU.png";
$dest = "nine-guy.png";

while (file_exists($dest)) {
    $dest = preg_replace_callback("/(\d+)?(\.[^\.]+)$/", function ($m) {
        return ($m[1] + 1) . $m[2];
    }, $dest);
}

copy($file, $dest);

You may need to be using a later version of PHP for the anonymous function callback; I tested with 5.3.10 and everything worked just fine.

like image 51
Sampson Avatar answered Dec 01 '25 12:12

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!