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];
Related
I have a php script which uploads files:
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
// File path
$path = '../pdf/'.$filename;
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
This works fine!
But I would like to modify the filename while uploading:
For example:
I uploading a "upload.pdf" file.
But I would like to get the name "upload_2021.pdf"
How can I realize it?
I found a solution !!
$path = '../pdf/'.$filename;
$extension = pathinfo($path, PATHINFO_EXTENSION);
$name = pathinfo($path, PATHINFO_FILENAME);
From what I can see, the only thing you need to do is change the $path variable.
Bare in mind, that what you are showing here is not a safe and secure upload script. You are not doing any file and mime-type validation what so ever. There is nothing preventing your users from uploading harmful files. Together with not checking for duplicate files and some other edge cases, think twice before putting this into production.
for($index = 0;$index < count($_FILES['files']['name']); $index++){
// File name
$filename = $_FILES['files']['name'][$index];
$parts = explode(".", $filename);
$year = date("Y");
// File path
$path = '../pdf/'.$parts[0] . '_' $year . '.' . $parts[count($parts)-1];
// Upload file
if(!move_uploaded_file($_FILES['files']['tmp_name'][$index],$path)){
// ERROR
exit;
}
}
a short example:
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
I am using Laravel and I have a form that uploading a file. And I want to save the full path of that file in my database. Do you know how?
if($request->hasFile('alternate_add_file_path')) {
$file = $request->file('alternate_add_file_path');
$destination = 'files/';
$extension = $file->getClientOriginalExtension();
$file_name = $getCreateDate . '_' . str_replace('/','_',$M_USER_NAME) . '.' . $extension;
$file->move($destination, $file_name );
}
This below is for the save into database
$M_FILE_PATH = $file_name;
I do not have an error though, just only the filename which saved into my database, not the full path.
To convert a relative path to an absolute one (server side) you can use realpath. Eg.
$fullpath = realpath($file_name);
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
<?php
require '../config.php';
// Edit upload location here
$result = 0;
$name = mysql_real_escape_string($_FILES['myfile']['name']);
$path = csv;
$ext = 'csv';
$md5 = md5($name);
$target_path = $path . '\\' . $md5 . '.' . $ext;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
}
sleep(1);
?>
It won't upload any files such as with the file names that contain brackets, etc.
Don't do:
$name = mysql_real_escape_string($_FILES['myfile']['name']);
Do:
$name = $_FILES['myfile']['name'];
you are getting the MD5 of $name so no reason to clean it as it will produce a 32-char hex string which will not contain any special characters regardless. If a filename contains special chars and you escape using the above the MD5 will completely change.
The error is likely here:
$path = csv;
Here PHP is looking for a constant with name csv unless you have defined that, it is going to return null, so your $target_path is not being built correctly.
Just one more thing to try is use the pre defined DIRECTORY_SEPERATOR constant while building your $target path so...
$target_path = $path . DIRECTORY_SEPERATOR . $md5 . '.' . $ext;