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

2019-01-15 18:13发布

问题:

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?

Thanks,

回答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)


回答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);


回答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");


回答4:

Thanks man, you give me the light.

I made something like this:

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

Using move_ulploaded_file and copy we can make only one thumb. :)