PHP: how do I copy a temp file upload to multiple places?

how can I copy two times the same file? I’m trying to do something like this:

                copy($file['tmp_name'], $folder."1.jpg");
            copy($file['tmp_name'], $folder."2.jpg");
            copy($file['tmp_name'], $folder."3.jpg");

And how many time does temp files has before it’s destroyed by the server?

I try using move_uploaded_file also, but I can’t make it work. I want to generate 2 thumbs from an uploaded file.

Some help?


Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

move_uploaded_file will move the file, and not copy it — which means it’ll work only once.

If you are using copy, there shouldn’t be any limit at all on the number of times you can copy : the temporay file created by the upload will only be destroyed at the end of the execution of your script (unless you move/delete it before, of course)

Still, maybe a solution would be to use move_uploaded_file first, and, then, copy ?

A bit like that, I suppose :

if (move_uploaded_file($file['tmp_name'], $folder . '1.jpg')) {
    copy($folder . '1.jpg', $folder . '2.jpg');
    copy($folder . '1.jpg', $folder . '3.jpg');

This would allow you to get the checks provided by move_uploaded_file

If this doesn’t work, then, make sure that :

  • $folder contains what you want — including the final /
  • That $file['tmp_name'] also contains what you want (I’m guessing this is some kind of copy of $_FILES — make sure the copy of $_FILES to $file is done properly)

Solution 2

Why doesn’t move_uploaded_file() work? Are you trying to use it twice? You can’t do that, it moves it, so the second time will fail.

I would just use move_uploaded_file() once, and then make the second copy from the location you just moved it to:

move_uploaded_file($uploaded, $destination);
copy($destination, $destination2);

Solution 3

I don’t have a reply to your question directly but how about this workaround ?

copy($file['tmp_name'], $folder."1.jpg");
copy($folder."1.jpg"  , $folder."2.jpg");
copy($folder."1.jpg"  , $folder."3.jpg");

Solution 4

Thanks man, you give me the light.

I made something like this:

    $objUpload = new Upload();
    $filename = $objUpload->uploadFile($newFile,$folder); 
// returns a string    
// makes a 139px thumbnail from the original file uploaded on the first step
// makes another thumb from the same file

Using move_ulploaded_file and copy we can make only one thumb. 🙂

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply