file rename while uploading - php

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

Related

File is writing into wrong path using PHP

I am uploading file into folder using PHP but my issue is its at a time writing file into 2 different path. My code is below.
if(array_key_exists('pimage',$_FILES)){
$tempFile = $_FILES['pimage']['tmp_name'];
$fileName = $_FILES['pimage']['name'];
$fileName = str_replace(" ", "-", $_FILES['pimage']['name']);
$fig = rand(1, 999999);
$saveFile = $fig . '_' . $fileName;
$uploadOk = 1;
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_GIF) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
}
if (exif_imagetype($_FILES['pimage']['tmp_name']) == IMAGETYPE_JPEG) {
$ext=pathinfo($saveFile, PATHINFO_FILENAME);
$saveFile=$ext.'.png';
$png = imagepng(imagecreatefromjpeg($_FILES['pimage']['tmp_name']), $saveFile);
}
if (strpos($fileName,'php') !== false) {
# code...
}else{
$targetPath = PT_USERS_IMAGES_UPLOAD;
$targetFile = $targetPath . $saveFile;
if (file_exists($targetFile)) {
$data=array("msg"=>'profile image already exists');
$uploadOk = 0;
}
if ($_FILES["pimage"]["size"] > 2000000 || $_FILES["pimage"]["size"] == 0) {
$uploadOk = 0;
$data=array("msg" => "profile image should not greater than 2 MB.");
}
//echo $uploadOk;exit;
if ($uploadOk==0) {
$flag=0;
$data[]=array("msg" => $data['msg']);
}else{
$moved =move_uploaded_file($tempFile, $targetFile);
if ($moved) {
$filename = $saveFile;
$data = array('ai_image' => $filename);
$this->db->where('accounts_id', $dataArr['user_id']);
$this->db->update('pt_operator_accounts', $data);
}else{
$flag=0;
$data[]=array("msg" => "Not uploaded because of error #".$_FILES["pimage"]["error"]);
}
// print_r($data);exit;
}
}
}
Here I need to write file into PT_USERS_IMAGES_UPLOAD path but before uploading into this path also the file is uploading into project's root path. Here I need to upload only in PT_USERS_IMAGES_UPLOAD path not in project's root path.
It is likely because of these lines:
imagepng(imagecreatefromgif($_FILES['pimage']['tmp_name']), $saveFile);
If you look at the documentation regarding this imagepng(), it will either output an image to the browser (with a proper header) or save the file to disk when you fill out the second parameter, in your case you have used the to parameter ($saveFile). So, once you save it there, you then save it again using the move_uploaded_file($tempFile, $targetFile); which is the one saving it to the proper location.
If you are trying to convert something to PNG, then just do the imagepng() line and remove the move_uploaded_file() line. Change $saveFile to T_USERS_IMAGES_UPLOAD and then you should only get one saved file. Either way, remove one of those methods for saving the file to disk.

Resumable Upload with ng-file-upload + PHP (Merging parts)

I'm trying to implement ng-file-upload with Resumable Uploads mode to split big files in chunks and merge them once uploaded. I have implemented ng-file-upload in many projects but it's my first time doing it to upload so big files.
My issue is that I don't know how to make it work the server side files in PHP. I've just got to upload chunks with diferents name but I can't merge them.
Could anybody post an example of server side code in PHP to make work this feature?
This is what I have done up to this point:
AngularJS
$scope.uploadMediaFile = function (file) {
if(file) {
Upload.upload({
ignoreLoadingBar: true,
url: 'app/api/upload/mediaFile.php',
resumeChunkSize: '1MB',
file: file
}).then(function (response) {
if(response.data.success) {
$scope.post.mediaFile = response.data.filename;
$scope.post.duration = response.data.duration;
} else {
console.error(response.data.error);
}
}, null, function (evt) {
console.log(part);
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
mediaFile.php
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
$file_ext = pathinfo($filename, PATHINFO_EXTENSION);
$file_des = $_SERVER['DOCUMENT_ROOT'] . '/storage/content/temp/';
if(!file_exists($file_des)) mkdir($file_des);
// Puting a diferent name for each file part
$new_filename = uniqid() . "." . pathinfo($filename, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp, $file_des . $new_filename)
So far, I get many pieces of same file with diferent names.
Just in case someone is looking similar question, I post my solution.
<?php
// File chunk
$filename = $_FILES['file']['name'];
$file_tmp = $_FILES['file']['tmp_name'];
// Defining temporary directory
$file_des = $_SERVER['DOCUMENT_ROOT'] . '/storage/content/temp/';
// If not exists, create temp dir.
if(!file_exists($file_des)) mkdir($file_des);
// The first chunk have the original name of file uploaded
// so, if it exists in temp dir, upload the other pieces
// with anothers uniques names
if(file_exists($file_des . $filename)) {
$new_name = uniqid() . "." . pathinfo($filename, PATHINFO_EXTENSION);
move_uploaded_file($file_tmp, $file_des . $new_name);
// Now, append the chunk file to the first base file.
$handle = fopen($file_des . $new_name, 'rb');
$buff = fread($handle, filesize($file_des . $new_name));
fclose($handle);
$final = fopen($file_des . $filename, 'ab');
$write = fwrite($final, $buff);
fclose($final);
// Delete chunk
unlink($file_des . $new_name);
} else {
/* MAKE SURE WE DELETE THE CONTENT OF THE DESTINATION FOLDER FIRST,
OTHERWISE CHUNKS WILL BE APPENDED FOR EVER
IN CASE YOU ARE TRYING TO UPLOAD A FILE WITH THE EXACT SAME NAME.
CAREFUL: YOU MAY PREFER TO DELETE ONLY THE FILE
INSTEAD OF THE FOLDER'S CONTENT, IN THE CASE
YOUR FOLDER CONTAINS MORE THAN ONE FILE.
*/
$files_to_delete = glob($file_des."*"); // get all file names
foreach($files_to_delete as $file) // iterate files
{
if(is_file($file))
{
unlink($file); // delete file
}
}
// First chunk of file with original name.
move_uploaded_file($file_tmp, $file_des . $filename);
}

How to check Image name in folder and rename it?

I have a csv file with image name and Prefix for image and I want to add prefix in that image name and rename it and move it to another directory.
<?php
$fullpath = '/var/www/html/john/Source/01-00228.jpg';
$additional = '3D_Perception_';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/' . $additional
. $info['filename']
. '.' . $info['extension'];
echo $fullpath ;
}
?>
Here Image file is store in Source Directory I want to rename it with some prefix and move it other directory like Destination
Please help me out to find solution for this.
<?php
$source_directory = '/var/www/html/john/Source/';
$dest_directory = '/var/www/html/john/Source/'; // Assuming you'll change it
$filename = '01-00228.jpg';
$prefix = '3D_Perception_';
$file = $source_directory . $filename;
$dest_file = $dest_directory . $prefix . $filename;
if (file_exists($file)) {
if (copy($file, $dest_file)) {
unlink($file); // Deleting source file.
var_dump(pathinfo($dest_file)); // Dump dest file infos, replace it with wathever you want to do.
} else {
// if copy doesn't work, do something.
}
}
?>
Try this, and take care about my comments. ;)

How to rename each file before uploading to server to a time-stamp

I'm using the following code to upload some files, but well, some get replaced since the names get to be alike. I just wanna know how do i change the name, i tried but i kinda find myself messing the entire code.
PHP
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
I would like each file to have something from this variable generated from time.
$rand_name = microtime().microtime().time().microtime();
Thanks.
I don't want to first check if file exists as that adds to the processes, i just want to use time() and some random string. to just get a unique name.
Please see this website for a decent example of file uploading and an explanation. Also this site appears to be where you found this particular script from or if not offers a good explanation.
I have modified your code to include some comments so you and others can understand what is going on better. In theory, the code shouldn't be overwriting existing files like you say it does but I have added what you would need to change to set the name of the file to a random string.
In addition you are storing the original filename into the session and not the modified filename.
define("UPLOAD_DIR", "/path/to/uploads/");
if (!empty($_FILES["ambum_art"]))
{
// The file uploaded
$myFile = $_FILES["ambum_art"];
// Check there was no errors
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// Rename the file so it only contains A-Z, 0-9 . _ -
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
// Split the name into useful parts
$parts = pathinfo($name);
// This part of the code should continue to loop until a filename has been found that does not already exist.
$i = 0;
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// If you want to set a random unique name for the file then uncomment the following line and remove the above
// $name = uniqid() . $parts["extension"];
// Now its time to save the uploaded file in your upload directory with the new name
$success = move_uploaded_file($myFile["tmp_name"], UPLOAD_DIR . '/'.$name);
// If saving failed then quit execution
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// Set file path to the $Dir variable
$Dir = UPLOAD_DIR .'/'. $name;
// Set the permissions on the newly uploaded file
chmod($Dir, 0644);
// Your application specific session stuff
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir; // Save the file path to the session
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
Read more about PHPs uniqid.
I would also strongly advise doing some filetype checking as currently it appears as though any file can be uploaded. The second link above has a section titled 'Security Considerations' that I would recommend reading through vary carefully.
This code is filtering the name, then checks if file with exactly same name is already sent. If it is - name is changed with with number.
If you want to change the file name as in many sites - you may modify this line $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
For example into: $name = time().'_'.preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
If user sends file calle 'hello.jpg' this code will change it to _hello.jpg if file with the same name exists already the name _hello-.jpg will be used instead.
First you need to copy that file which you want to upload and after that you have to rename that. Ex.
//copy
if (!copy($file, $newfile)) {
echo "failed to copy $file...\n";
}
?>
//rename
rename('picture', 'img506.jpg');
Reference Link for copy
Rename file
Edited:
Replace your code with this and then try
<?php
if (!empty($_FILES["ambum_art"])) {
$myFile = $_FILES["ambum_art"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
if (file_exists($myFile["name"])) {
rename($myFile["name"], $myFile["name"].time()); //added content
}
$success = move_uploaded_file($myFile["tmp_name"],UPLOAD_DIR . '/'.$name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
} else {
$Dir = UPLOAD_DIR .'/'. $_FILES["ambum_art"]["name"];
}
chmod(UPLOAD_DIR .'/'. $name, 0644);
unset($_SESSION['video']);
$_SESSION['album_art'] = $Dir;
$ambum_art_result = array();
$ambum_art_result['content'] = $Dir;
echo json_encode($ambum_art_result);
}
?>
This will rename your existing file and then copy your file

PHP fileupload: keep both files if same name

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!

Categories