I am uploading three files using Zend Element File. I am uploading and renaming the files. Now the problem is that when uploading same extension, it generates error of
Zend_Filter_Exception: File 'D:\wamp2\tmp\php2443.tmp' could not be renamed. It already exists.
For example if in first file I upload file of extenstiono .txt in second I upload .docx and in third I again select .txt or .docx, It will generate the above given error.
But If I select three different extensions, every thing goes best. I am using the following code
if ($form->med_file_1->isUploaded()) {
$originalFilename = pathinfo($form->med_file_1->getFileName());
$newFilename = time() . '.' . $originalFilename['extension'];
$form->med_file_1->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
$form->med_file_1->receive();
}
if ($form->med_file_2->isUploaded()) {
$originalFilename = pathinfo($form->med_file_2->getFileName());
$newFilename = time() . '.' . $originalFilename['extension'];
$form->med_file_2->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
$form->med_file_2->receive();
}
if ($form->med_file_3->isUploaded()) {
$originalFilename = pathinfo($form->med_file_3->getFileName());
$newFilename = time() . '.' . $originalFilename['extension'];
$form->med_file_3->addFilter('Rename', "application_data/uploaded_files/patients/" . $newFilename,$originalFilename['basename']);
$form->med_file_3->receive();
}
The reason for the error is because you are naming each uploaded file:
time() . '.' . $originalFilename['extension'];
The call to receive() happens so fast that time() returns the same value on each call so you can end up with duplicate file names. You just need to generate a more unique name for each file. Something like the following should work:
md5(uniqid(time(), true)) . '.' . $originalFilename['extension'];
//or
$originalFilename['basename'] . '_' . time() . '.' . $originalFilename['extension'];
Related
I am trying to upload image files to a server and creating a random name when doing so. The issue I am having is that sometimes (far too often) it creates the same file name but for files with a different extension.
My code for the upload is below, what I want to do is add a check to make sure the name is not in use but with a different extension.
Example -
da4fb5c6e93e74d3df8527599fa62642.jpg & da4fb5c6e93e74d3df8527599fa62642.JPG
if ($_FILES['file']['name']) {if (!$_FILES['file']['error']){
$name = md5(mt_rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = $_SERVER['DOCUMENT_ROOT'] . '/images/infopages/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo '/images/infopages/' . $filename;
}else{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Any help is appreciated.
You can use PHP uniqid & rand functions combinedly. In this way you will never get duplicate values.
$filename = uniqid (rand(1000000,9999999), true) '.' . $ext[1];
I have my upload php code where my intent is , obtained file from $_files,
add a random number between 0 and 9999 to the name of image like this:
image sent : image.jpg
before saving : image321.jpg
the image is saved in my upload folder but the filename are like
"php2983204tmp"
if ($file !== null) {
$rand = rand(0000,9999);
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
any ideas to fix?
The filename in your example is php and your extension is tmp. None of them have the . that you are missing.
You need to add the dot . as a string after the $file_name and $rand, before the $extension like this:
$file->move($path, $file_name.$rand. "." .$extension);
TIME is always unique identity, use it as below (maybe helpful):
if ($file !== null) {
$rand = rand(0000,9999).time();
$path = "some_path";
$file_name = $file->getClientOriginalName(); // file
$extension = $file->getClientOriginalExtension(); // jpg
$file->move($path, $file_name.$rand.$extension);
$response = "File loaded successfully: " . $file_name.$extension;
$response .= '<br>size: ' . filesize($path . '/' . $file->getClientOriginalName()) / 1024 . ' kb';
return new Response($response);
You need add in the desired chars to the actual string.
$file->move($path, $file_name.$rand.".".$extension);
But I have to say, I am against how you've done this, you don't even check if the "newly" created string already exists in the directory. Its better to hash the time of upload with the original filename, rename the file to the new hash and use a database to point to the file as this way the filename collisions don't occur.
$fn = md5(microtime(true) . $extension . $file_name);
$file->move($path, $fn);
Having some trouble with rewriting a photo file. I need the file name to get rewritten as a random string. The file uploads fine - I can't seem to get it copy the file and rewrite the file name to the random string. The file is going to stay in the directory.
The function is working fine and I can rewrite file name in the database, but it will not rewrite the actual file in the folder. The folder permissions are rwxr-xr-x (755).
Any thoughts?
function AfterUpdate(){
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . $newFilename;
if (move_uploaded_file($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}
}
$newFilename contains a path location I guess by looking at the $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];.
$newFilename should just be the new file name with extension.
move_uploaded_file will only move files from one folder to another or the same, that already exists. But will not create a folder for you.
Simple fix. Replace move_uploaded_file with rename. The file will not be moved, just renamed.
$file = $this->file_attachment;
$path_parts = pathinfo($file);
$newFilename = $path_parts['dirname'] . "/" . uniqid() . "." . $path_parts['extension'];
$file_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $file;
$newfile_src = $_SERVER['DOCUMENT_ROOT'] . "/" . $newFilename;
if (rename($file_src, $newfile_src)){
$this->file_attachment = $newFilename;
}
I'm trying to rename the input file to be a .jpg after conversion, but for some reason I'm getting a file.png.jpg when I'm really looking for file.jpg
Here is my code:
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
Use pathinfo():
$source = $path . $_POST['username']. "-" . $_FILES['t1']['name'];
$path_parts = pathinfo( $_FILES['t1']['name'] );
$destination = $path . $_POST['username']. "-" . $path_parts['filename'] . ".jpg";
Let's say that the variable $filename contains your image name with the png extension.
In order to change the extension to jpg , simply run it through this function :
function replace_extension($filename) {
return preg_replace('/\..+$/', '.' . '.jpg', $filename);
}
The basename() function includes the original files extension
Use the pathinfo() function to return an array of informatino about the file and use the filename with out the extension
Replace
$destination = $path . $_POST['username']. "-" . basename($_FILES['t1']['name']) . ".jpg";
with
$info = pathinfo($_FILES['t1']['name']);
$destination = $path . $_POST['username']. "-" . $info['filename'] . ".jpg";
You can either use the second parameter to basename to kill the suffix
$filename = basename($_FILES['t1']['name'], ".png");
or you could do some string manipulation
$filename = substr($_FILES['t1']['name],0, strrpos($_FILES['t1']['name'], ".") -1);
basename returns you the whole filename, including the file type suffix (i.e. ".jpg"). If you want to strip the suffix, you can call the function with a second parameter: basename($_FILES['t1']['name'], 'png').
But if you want to convert a png to a jpg, you can't just change the filename, you have to convert the file using special functions, see "Use PHP to convert PNG to JPG with compression?".
Who can help me to fix the following problem? Here is the issue: in a form POST i made people can upload files. The code below check if in the "uploads" folder there another file with the same name. If so, files are renamed as this example:
hallo.txt
1_hallo.txt
2_hallo.txt
... and so on.
This is the code used:
$OriginalFilename = $FinalFilename = $_FILES['uploaded']['name'];
// rename file if it already exists by prefixing an incrementing number
$FileCounter = 1;
while (file_exists( 'uploads/'.$FinalFilename ))
$FinalFilename = $FileCounter++.'_'.$OriginalFilename;
I would like to rename files in a different way. progressive numbers should be AFTER the file and, of course, before the extention. This is the same example of before but in the way i want:
hallo.txt
hallo_1.txt
hallo_2.txt
... and so on.
How can i modify the code to reach that result?
Thank you in advance and sorry for my newbie-style question. I'm really newbie! :)
Mat
Just change the $FinalFilename:
$FinalFilename = pathinfo($OriginalFilename, PATHINFO_FILENAME) . '_' . $FileCounter++ . '.' . pathinfo($OriginalFilename, PATHINFO_EXTENSION);
Or (better if you have a lot of files with the same name and often iterate more than once):
$filename = pathinfo($OriginalFilename, PATHINFO_FILENAME);
$extension = pathinfo($OriginalFilename, PATHINFO_EXTENSION);
while (file_exists( 'uploads/'.$FinalFilename ))
$FinalFilename = $filename . '_' . $FileCounter++ . '.' . $extension;