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

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,

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)

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

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

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. :)

Related

Image uploader working perfectly for an insert form but not for an update form

I know there are already many similar questions like this and I apologize in advance for adding to the file, but I am a little short on time to do research and I need quick help. I am trying to finish an overdue assignment and my image upload function is working perfectly when I add a product, but not when I update it. I have no idea why. My code to update the image is here:
require_once 'file-util.php'
// Check if the file exists before setting it
if (isset($_FILES['imageFile1'])) {
// Retrieve the name of the file based on what it was called on the client computer
$filename = $codeInput . '.png';
// Make sure the filename exists
if (!empty($filename)) {
// Store the temporary location of where the file was stored on the server
$sourceLocation = $_FILES['imageFile1']['tmp_name'];
// Build the path to the images folder and use the same filename as before
$targetPath = $image_dir_path . DIRECTORY_SEPARATOR . $filename;
// Move file from temp directory to images folder
move_uploaded_file($sourceLocation, $targetPath);
}
}
This is the exact same code that I have in my insert_product file.
And my file_util is here:
$image_dir = 'images';
$image_dir_path = getcwd() . DIRECTORY_SEPARATOR . $image_dir;
Everything else works perfectly, but it is just this little thing that isn't seeming to do anything, so it seems to me like there's a little detail I'm missing for this to work in update_product. Is there something else I need to do to get this to work, or is it something else I'm unaware of?
Edit: Turns out that I just forgot to set the encryption type in my add_product_form. If anyone else has this silly issue, double check your forms for this near the top of the body:
<form action="insert_product.php" method="post"
id="add_product_form"
enctype="multipart/form-data">
You need to check if your updating form tag has the proper enctype attribute value...
and please be aware to use more validation on the uploaded file, your checking for file name exists or not will always be true as you are setting a value for it in the previous line.
Apparently, my code was right but I just forgot to go "enctype="multipart/form-data" in update_product_form.php.

Database does not have enough time to save the record

I am working on a project on CakePHP 2.4.4. And I am facing the following problem: My Vendor Uploading Class calls one function newImage which creates a new image. When I upload more than one image for example five times, this function is being called five time in a row. This function contains code like:
...
...initializing Uploader class
...
//creating image
$this->Orderimage->create();
$data = array(
'order_id' => $order_id,
'filename' => $filename,
'date' => date('Y-m-d'),
'extension' => $result['ext'],
);
$this->Orderimage->save($data);
But here is the place where I meet my problem. When I am trying to upload more than 4 images, which means that I call this function more than 4 times in a row some image are not uploaded and instead of them the previous pictures are uploaded. The reason for this is that these images are getting the same filename. But the filename is given by the last created image+1. Therefore the bug is that the database does not have enough time to save the image, when the next arrives. And this is the reason, that some image overwrite another. How could I fix it ?
Try setting the filename as something unique instead of just using +1.
For example:
$filename = CakeText::uuid() . '.jpg'; // or try String::uuid()
That way you don't need to worry about accidentally having the same filename.
https://book.cakephp.org/2.0/en/core-utility-libraries/string.html#CakeText::uuid
Side note: if you're uploading a lot of files into a single directory, it's a good idea to put them in nested directories (3 deep is common). For example something like:
$filename = rand(0,99) . DS . rand(0,99) . DS . rand(0,99) . $file;
If you did it this way, it'd be very unlikely you'll have the same filename+number combination in the same folder. Just store the path as well as the filename, and you're good to go. This will keep a single folder from having so many images that it takes forever to view as well.
NOTE: I just wrote this code off the top of my head - I did not verify it for syntax...etc, but it should give you the idea.
Daves solution should solve your problem but if you insist to user your filename convention, get the last inserted id and create all images in a loop with $lastInsertedId + $counter bevore saving them. Write the hole image array afterwards to your db.
NOTE: You should use this solution only if you have no simultaneous write requests!

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

php image uploader need it to be simple

I need to get this done very quickly. What's an easy way to do image uploading in php...I have a script atm but if an image with the same name comes it'll overwrite it.
Basically I just want to be able to use the form field file to select an image and upload and maybe rename it somehow. Then put the location into a database to retrieve when needed.
Any tips or ideas on how to do this? Don't have a lot of time to get this done.
http://www.google.co.za/search?sourceid=chrome&ie=UTF-8&q=php+image+upload
http://www.plupload.com/ - is also a good way to do this. Doing something
very quickly ... the easy way
Sounds to me like you are looking for the easy way out. Please remember that we are not here to give you your code solution, but merely as an advisory panel to help you get over some obstacles in your current (already tried to make it work) code. If you read up a bit its real easy, thats the reason for documentation on everything, especially PHP and file uploading.
:)
Seems to me right now, your script has a security issue as well.
Append a unique hash to the end of the filename before you save it. That way no one can overwrite your files.
Can you just append uniqid() to the filename..?
$target = "files/";
// Upload the file to directory
$url = basename($_FILES['uploadedfile']['name']);
$name = str_replace(' ', '_', $url);
$target .= strtolower($name . uniqid());
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target))
{
echo 'File has been uploaded<br />
http://yoursite.com/directory/' . $target . '';
}
Obviously still needs to be made more secure.

I made an upload script in PHP. How do I avoid overwriting files?

I've made an image upload script using the move_uploaded_file function. This function seems to overwrite any preexisting file with the new one. So, I need to check if the target location already has a file. If it does then I need to append something to the filename(before the extension so that the file name is still valid) so the filename is unique. I'd like to have the change be minimal instead of something like appending the datetime, if possible.
How can I do this with PHP?
When uploading files I will nearly always rename them. Typically there will be some kind of database record for that file. I use the ID of that to guarantee uniqueness of the file. Sometimes I'll even store what the client's original filename was in the database too but I'll never keep it or the temporary name because there is no guarantee that information is good, that your OS will support it or that it's unique (which is your issue).
So just rename it to some scheme of your own devising. That's my advice.
If you don't have any database reference, then you could use file_exists() for this but there's no guarantee that between the time of checking if something exists and moving it that something else won't use that same filename that you'll then overwrite. This is a classic race condition.
http://us3.php.net/manual/en/function.file-exists.php
Don't use file_exists() for the reason that it returns true (on *nix systems at least, since directories are specialized files) if the value is a directory. Use is_file() instead.
For example, say something fails and you have a string like:
$path = "/path/to/file/" . $file; // Assuming $file is an empty value, if something failed for example
if ( true === file_exists($path) ) { echo "This returns true"; }
if ( true === is_file($path) ) { echo "You will not read this"; }
It's caused a few problems in the past for me, so I always use is_file() rather than file_exists().
I use date and time functions to generate a random file name based on the time of upload.
Let's assume you are submitting a file from a form where you have an input named incomingfile like this:
<input type="file" id="incomingfile" name="incomingfile" />
First of all I use to "depure" the filename and copy it from the default temporary directory to a temporary directory. This is necessary to deal with special characters. I had troubles when I didn't adopt this practice.
$new_depured_filename = strtolower(preg_replace('/[^a-zA-Z0-9_ -.]/s', '_', $_FILES["incomingfile"]["name"]));
copy($_FILES["incomingfile"]["tmp_name"], 'my_temp_directory/'.$new_depured_filename);
With the following piece of code I check if the file exists, if so, I find a new name and finally copy it. For example if I want to write a file called myimage.jpg and it already exists I rename the pending file to myimage__000.jpg. If this exists as well I rename the pending file to myimage__001.jpg and so on until I find a non-existing filename.
$i=0; // A counter for the tail to append to the filename
$new_filename = $new_depured_filename;
$new_filepath='myfiles/music/'.$new_filename;
while(file_exists($new_filepath)) {
$tail = str_pad((string) $i, 3, "0", STR_PAD_LEFT); // Converts the integer in $i to a string of 3 characters with left zero fill.
$fileinfos = pathinfo($new_filepath); // Gathers some infos about the file
if($i>0) { // If we aren't at the first while cycle (where you have the filename without any added strings) then delete the tail (like "__000") from the filename to add another one later (otherwise you'd have filenames like myfile__000__001__002__003.jpg)
$previous_tail = str_pad((string) $i-1, 3, "0", STR_PAD_LEFT);
$new_filename = str_replace('__'.$previous_tail,"",$new_filename);
}
$new_filename = str_replace('.'.$fileinfos['extension'],"",$new_filename); // Deletes the extension
$new_filename = $new_filename.'__'.$tail.'.'.$fileinfos['extension']; // Append our tail and the extension
$new_filepath = 'myfiles/music/'.$new_filename; // Crea il nuovo percorso
$i++;
}
copy('my_temp_directory/'.$new_depured_filename, $new_filepath); // Finally we copy the file to its destination directory
unlink('my_temp_directory/'.$new_depured_filename); // and delete the temporary one
Used functions:
strtolower
preg_replace
copy
file_exists
str_pad
pathinfo
str_replace
unlink
To check if a file exists, you can use the file_exists function.
To cut the filename, you can use the pathinfo function.
I use
$file_name = time() . "_" . $uploaded_file_name;

Categories