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;
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 am trying to upload a file using laravel Storage i.e
$request->file('input_field_name')->store('directory_name'); but it is saving the file in specified directory with random string name.
Now I want to save the uploaded file with custom name i.e current timestamp concatenate with actual file name. Is there any fastest and simplest way to achive this functionality.
Use storeAs() instead:
$request->file('input_field_name')->storeAs('directory_name', time().'.jpg');
You can use below code :
Use File Facade
use Illuminate\Http\File;
Make Following Changes in Your Code
$custom_file_name = time().'-'.$request->file('input_field_name')->getClientOriginalName();
$path = $request->file('input_field_name')->storeAs('directory_name',$custom_file_name);
For more detail : Laravel Filesystem And storeAs as mention by #Alexey Mezenin
Hope this code will help :)
You also can try like this
$ImgValue = $request->service_photo;
$getFileExt = $ImgValue->getClientOriginalExtension();
$uploadedFile = time()'.'.$getFileExt;
$uploadDir = public_path('UPLOAS_PATH');
$ImgValue->move($uploadDir, $uploadedFile);
Thanks,
Try with following work :
$image = time() .'_'. $request->file('image')->getClientOriginalName();
$path = base_path() . '/public/uploads/';
$request->file('image')->move($path, $image);
You can also try this one.
$originalName = time().'.'.$file->getClientOriginalName();
$filename = str_slug(pathinfo($originalName, PATHINFO_FILENAME), "-");
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
$path = public_path('/uploads/');
//Call getNewFileName function
$finalFullName = $this->getNewFileName($filename, $extension, $path);
// Function getNewFileName
public function getNewFileName($filename, $extension, $path)
{
$i = 1;
$new_filename = $filename . '.' . $extension;
while (File::exists($path . $new_filename))
$new_filename = $filename . '_' . $i++ . '.' . $extension;
return $new_filename;
}
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 having a strange issue with a component I'm working on. The component has a form that includes a file upload. The code checks for duplicate filenames and appends a counter to the end. All of this works perfectly except with I try and modify the record and change the associated file.
I used component creator to build the skeleton at that code works for updates -
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
//Add Timestamp MD5 to avoid overwriting
$filename = md5(time()) . '-' . implode('.',$filename);
$uploadPath = '/var/www/plm_anz/' . $filename;
$fileTemp = $file['tmp_name'];
if(!JFile::exists($uploadPath)){
if (!JFile::upload($fileTemp, $uploadPath)){
JError::raiseWarning(500, 'Error moving file');
return false;
}
}
$array['ping_location'] = $filename;
When I update the code to remove the MD5 sum and append the counter it all falls apart..
//Replace any special characters in the filename
$filename = explode('.', $file['name']);
$filename[0] = preg_replace("/[^A-Za-z0-9]/i", "-", $filename[0]);
$originalFile = $finalFile = $file['name'];
$fileCounter = 1;
//Rename duplicate files
$fileprefix = pathinfo($originalFile, PATHINFO_FILENAME);
$extension = pathinfo($originalFile, PATHINFO_EXTENSION);
while (file_exists( '/var/www/plm_anz/'.$finalFile )){
$finalFile = $fileprefix . '_' . $fileCounter++ . '.' . $extension;
}
$uploadPath = '/var/www/plm_anz/' . $finalFile;
$fileTemp = $file['tmp_name'];
if (!JFile::upload($fileTemp, $uploadPath)){
$fileMessage = "Error moving file - temp file:". $fileTemp . " Upload path ". $uploadPath;
JError::raiseWarning(500, $fileMessage);
return false;
}
I've narrowed down the cause to the filename that the while loop creates but cannot figure out why it only breaks the form update and not the new form submission.
The error I get in Joomla (3.4) is:
Error
Error moving file - temp file:/tmp/phpgwag5r Upload path
/var/www/plm_anz/com_hotcase_6.zip
Save failed with the following error:
I know it's something simple but I've been staring at it too long to see it!
Thanks!
Ok as it is I can not see any good reason why is failing.
The only thing I can suggest you is that JFile::upload is failing go to debug in /libraries/joomla/filesystem/file.php#449 and step by step try to understand what's wrong.
That's actually the file and line of JFile::upload.
In there probably the only line that matter to you is line 502 which is :
if (is_writeable($baseDir) && move_uploaded_file($src, $dest))
Especially try to see what's going on the variable $ret.
here is my problem i need to rename the images when someone upload it, i want to use date and time and to created the $datatime value and i dont know how to make it works can some tell me how to do it? any help much be appreciated... Much Thanks
<?php if(isset($_POST['action'])=='uploadfiles') {
$time = time();
$date = date('Y-m-d');
$datetime = "$time" . "$date";
$upload_directory ='uploads/';
$count_data =count($_FILES['data']) ;
$upload = $_FILES['data']['name'][$x].',';
for($x=0;$x<$count_data;$x++) {
$upload .= $_FILES['data']['name']["$x" . ""].',';
move_uploaded_file($_FILES['data']['tmp_name'][$x], $upload_directory . $_FILES['data']['name'][$x]); ##### upload into your directory }
//echo "upload successfully..";
$con="INSERT INTO inmuebles (foto1) values ('$upload')";
$query=mysql_query($con); } ?>
Change here:
move_uploaded_file(
$_FILES['data']['tmp_name'][$x],
$upload_directory . $datetime . $_FILES['data']['name'][$x]
); ##### upload into your directory
Here the $datetime should be the string containing the timestamp.
Try the following:
$ext = pathinfo($_FILES['data']['name'][$x], PATHINFO_EXTENSION);
$newname = $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
This will replace the current filename, and maintain the extension of the originally uploaded file.
If you want to maintain the original filename and simply append the datetime to it, use the following:
$info = pathinfo($_FILES['data']['name'][$x]);
$ext = $info['extension'];
$name = $info['filename'];
$newname = $name . $datetime . '.' . $ext;
move_uploaded_file($_FILES['data']['tmp_name'][$x],
$upload_directory . $newname);
Using date and time is a poor way to uniquely label anything because the limit of your fidelity is 1 item per second and computers are WAY faster than that, along with the fact more than 1 person could be using the upload at the same time. Instead use something build for this such as UUID (aka GUIDs). You can just use the uniqid() function in PHP which is very basic or if you read the comments somebody has written a UUID function (use version 5).
http://php.net/manual/en/function.uniqid.php