rename file while uploading with php - php

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

Related

Create random filename but check it's not already used

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

Joomla Development - Failed to move file

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.

how to add number in picture when upload if same file name of picture

I have this code for upload
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photo/" . $_FILES["image"]["name"]);
$location="photo/" . $_FILES["image"]["name"];
then the insert $location code for sql to add
The Question is how to have my picture file name number add ex: if i have "Picture.jpg "uploaded if i will upload again and same file name the output of the filename will be Picture(1).jpg and if I upload again with the same file name the output filename will be Picture(2).jpg and so on I want the "()" to increment if ever i will upload same file name. thanks in advance ^^
This can be achived with loop:
$info = pathinfo($_FILES['image']['name']);
$i = 0;
do {
$image_name = $info['filename'] . ($i ? "_($i)" : "") . "." . $info['extension'];
$i++;
$path = "photo/" . $image_name;
} while(file_exists($path));
move_uploaded_file($_FILES['image']['tmp_name'], $path);
You should also sanitize input file name:
string sanitizer for filename
Sanitizing strings to make them URL and filename safe?
If you want to have a unique image name after upload even if they have same name or they are uploading in loop means multiple upload.
$time = time() + sprintf("%06d",(microtime(true) - floor(microtime(true))) * 1000000);
$new_name=$image_name.'_'.$time.'.'.$extension
You can add the image name with a unique time stamp which differ each nano seconds and generate unique time stamp
This code is untested, but I would think something along the lines of:
if (file_exists('path/to/file/image.jpg')){
$i = 1;
while (file_exists('path/to/file/image ('.$i.').jpg')){
$i++;
}
$name = 'image ('.$i.');
}
And then save the image to $name. (which at some point will result in image (2).jpg)
try this
$path = "photo/" . $_FILES["image"]["name"];
$ext = pathinfo ($path, PATHINFO_EXTENSION );
$name = pathinfo ( $path, PATHINFO_FILENAME ] );
for($i = 0; file_exists($path); $i++){
if($i > 0){
$path = "photo/" .$name.'('.$id.').'.$ext;
}
}
echo $path;
Can you try this,
$name = $_FILES['image']['name'];
$pathinfo = pathinfo($name);
$FileName = $pathinfo['filename'];
$ext = $pathinfo['extension'];
$actual_image_name = $FileName.time().".".$ext;
$location="photo/".$converted_name;
if(move_uploaded_file($tmp, $location))
{
}

Having trouble with explode() in uploadify.php

I have this snippet from my uploadify.php:
if (!empty($_FILES)) {
$name = $_FILES['Filedata']['name'];
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
$path = pathinfo($targetFile);
// this portion here will be true if and only if the file name of the uploaded file does not contain '.', except of course the dot(.) before the file extension
$count = 1;
list( $filename, $ext) = explode( '.', $name, );
$newTargetFile = $targetFolder . $filename . '.' . $ext;
while( file_exists( $newTargetFile)) {
$newTargetFile = $targetFolder . $filename . '(' . ++$count . ')' . '.' . $ext;
}
// Validate the file type
$fileTypes = array('pdf'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$newTargetFile);
echo $newTargetFile;
} else {
echo 'Invalid file type.';
}
return $newTargetFile;
}
Basically this is quite working. Uploading the file and getting the path of the file which will then be inserted on the database and so on. But, I tried uploading a file which file name looks like this,
filename.1.5.3.pdf
and when succesfully uploaded, the file name then became filename alone, without having the file extension and not to mention the file name is not complete. From what I understood, the problem lies on my explode(). It exploded the string having the delimiter '.' and then assigns it to the variables. What will I do to make the explode() cut the string into two where the first half is the filename and the second is the file extension? PLease help.
Don't use explode, use a function designed for the job: pathinfo()
$ext = pathinfo($_FILES['Filedata']['name'], PATHINFO_EXTENSION);

file rename while uploading

I have a problem here im trying to upload a file
first time it is moving the filename from temp it its respective directory,
but again i try ot upload the aa different file with the same name it should rename the
first time uploaded file
with date_somefilename.csv and give the filename to its original state
for example a file test.csv ,im uploading it for first time it will upload to
corresponding directory as
test.csv,when i upload a different csv file with same name test.csv
I need to get the
test.csv (latest uploaded file)
06222012130209_test.csv(First time uploaded file)
The code is below
$place_file = "$path/$upload_to/$file_name";
if (!file_exists('uploads/'.$upload_to.'/'.$file_name))
{
move_uploaded_file($tmp, $place_file);
}else{
move_uploaded_file($tmp, $place_file);
$arr1 = explode('.csv',$file_name);
$todays_date = date("mdYHis");
$new_filename = $todays_date.'_'.$arr1[0].'.csv';
echo $str_cmd = "mv " . 'uploads/'.$upload_to.'/'.$file_name . " uploads/$upload_to/$new_filename";
system($str_cmd, $retval);
}
See comments in code.
$place_file = "$path/$upload_to/$file_name";
if (!file_exists($place_file)) {
move_uploaded_file($tmp, $place_file);
} else {
// first rename
$pathinfo = pathinfo($place_file);
$todays_date = date("mdYHis");
$new_filename = $pathinfo['dirname'].DIRECTORY_SEPARATOR.$todays_date.'_'.$pathinfo['basename'];
rename($place_file, $new_filename)
// and then move, not vice versa
move_uploaded_file($tmp, $place_file);
}
DIRECTORY_SEPARATOR is php constant. Value is '/' or '\', depending of operation system.
pathinfo() is php function, that return information about path: dirname, basename, extension, filename.
What about...
$place_file = "$path/$upload_to/$file_name";
if (file_exists($place_file)) {
$place_file = date("mdYHis")."_".$file_name;
}
if (!move_uploaded_file($tmp, $place_file)) {
echo "Could not move file";
exit;
}
I would not add a date to the file if it already exists. Instead I would just add a number to the end of it. Keep it simple.
$counter = 0;
do {
// destination path path
$destination = $path.'/'.$upload_to.'/';
// get extension
$file_ext = end(explode('.', $file_name));
// add file_name without extension
if (strlen($file_ext))
$destination .= substr($file_name, 0, strlen($file_name)-strlen($file_ext)-1);
// add counter
if ($counter)
$destination .= '_'.$counter;
// add extension
if (strlen($file_ext))
$destination .= $file_ext;
$counter++;
while (file_exists($destination));
// move file
move_uploaded_file($tmp, $destination);
$target = "uploads/$upload_to/$file_name";
if (file_exists($target)) {
$pathinfo = pathinfo($target);
$newName = "$pathinfo[dirname]/" . date('mdYHis') . "_$pathinfo[filename].$pathinfo[extension]";
rename($target, $newName);
}
move_uploaded_file($tmp, $target);
Beware though: Security threats with uploads.
how about something like this?
<?php
$tmp = '/tmp/foo'; // whatever you got out of $_FILES
$desitnation = '/tmp/bar.xyz'; // wherever you want that file to be saved
if (file_exists($desitnation)) {
$file = basename($destination)
$dot = strrpos($file, '.');
// rename existing file to contain its creation time
// "/temp/bar.xyz" -> "/temp/bar.2012-12-12-12-12-12.xyz"
$_destination = dirname($destination) . '/'
. substr($file, 0, $dot + 1)
. date('Y-m-d-H-i-s', filectime($destination))
. substr($file, $dot);
rename($destination, $_destination);
}
move_uploaded_file($tmp, $destination);

Categories