How can I change name of uploaded file in Laravel 4.
So far I have been doing it like this:
$file = Input::file('file');
$destinationPath = 'public/downloads/';
if (!file_exists($destinationPath)) {
mkdir("./".$destinationPath, 0777, true);
}
$filename = $file->getClientOriginalName();
But if I have 2 files with the same name I guess it gets rewritten, so I would like to have something like (2) added at the end of the second file name or to change the file name completely
The first step is to check if the file exists. If it doesn't, extract the filename and extension with pathinfo() and then rename it with the following code:
$img_name = strtolower(pathinfo($image_name, PATHINFO_FILENAME));
$img_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
$filecounter = 1;
while (file_exists($destinationPath)) {
$img_duplicate = $img_name . '_' . ++$filecounter . '.'. $img_ext;
$destinationPath = $destinationPath . $img_duplicate;
}
The loop will continue renaming files as file_1, file_2 etc. as long as the condition file_exists($destinationPath) returns true.
I know this question is closed, but this is a way to check if a filename is already taken, so the original file is not overwriten:
(... in the controller: ... )
$path = public_path().'\\uploads\\';
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$original_filename = pathinfo($fileName, PATHINFO_FILENAME);
$new_filename = $this->getNewFileName($original_filename, $extension, $path);
$upload_success = Input::file('file')->move($path, $new_filename);
this function get an "unused" filename:
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;
}
Related
I created a page that can upload file to my database, but when a filename has (.), it doesnt save properly. For example I upload a file named imagefile.50.jpg, it just saves as image20.50
<?php
function upload_image()
{
if(isset($_FILES["user_image"]))
{
$extension = explode('.', $_FILES['user_image']['name']);
$new_name = $extension[0] . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['user_image']['tmp_name'], $destination);
return $new_name;
}
}
To get the filename and extension of a file, you can use pathinfo, i.e.:
$file = "some_dir/somefile.test.php"; # $_FILES['user_image']['name']
$path_parts = pathinfo($file);
$fn = $path_parts['filename'];
$ext = $path_parts['extension'];
print $fn."\n";
print $ext;
Output:
somefile.test
php
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))
{
}
is there any pretty solution in PHP which allows me to expand filename with an auto-increment number if the filename already exists? I dont want to rename the uploaded files in some unreadable stuff. So i thought it would be nice like this: (all image files are allowed.)
Cover.png
Cover (1).png
Cover (2).png
…
First, let's separate extension and filename:
$file=pathinfo(<your file>);
For easier file check and appending, save filename into new variable:
$filename=$file['filename'];
Then, let's check if file already exists and save new filename until it doesn't:
$i=1;
while(file_exists($filename.".".$file['extension'])){
$filename=$file['filename']." ($i)";
$i++;
}
Here you go, you have a original file with your <append something> that doesn't exist yet.
EDIT:
Added auto increment number.
Got it:
if (preg_match('/(^.*?)+(?:\((\d+)\))?(\.(?:\w){0,3}$)/si', $FILE_NAME, $regs)) {
$filename = $regs[1];
$copies = (int)$regs[2];
$fileext = $regs[3];
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
while(file_exists($fullfile) && !is_dir($fullfile))
{
$copies = $copies+1;
$FILE_NAME = $filename."(".$copies.")".$fileext;
$fullfile = $FILE_DIRECTORY.$FILE_NAME;
}
}
return $FILE_NAME;
You can use this function below to get unique name for uploading
function get_unique_file_name($path, $filename) {
$file_parts = explode(".", $filename);
$ext = array_pop($file_parts);
$name = implode(".", $file_parts);
$i = 1;
while (file_exists($path . $filename)) {
$filename = $name . '-' . ($i++) . '.' . $ext;
}
return $filename;
}
Use that function as
$path = __DIR__ . '/tmp/';
$fileInput = 'userfile';
$filename = $path .
get_unique_file_name($path, basename($_FILES[$fileInput]['name']));
if (move_uploaded_file($_FILES[$fileInput]['tmp_name'], $filename)) {
return $filename;
}
You can get working script here at github page
Use file_exists() function and rename() function to achieve what you're trying to do!
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);
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);