How to check Image name in folder and rename it? - php

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

Related

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: search in other directories if image is exist and print the image

ok I edited my answer i found out how to find the file in the directories but my problem is it won't print the image. here's my code.
<?php
$file = 'testimage.png';
$dir = array(
$_SERVER['DOCUMENT_ROOT'] . "/folderA/",
$_SERVER['DOCUMENT_ROOT'] . "/folderB/"
);
foreach($dir as $d)
{
if(file_exists( $d . $file ))
{
$file = $file;
}
}
$imgPng = imageCreateFromPng($file);
header("Content-type: image/png");
imagePng($imgPng);
?>
why is not printing the image?
One way to do this without adding a bunch of code would be to set up the include_path to look in the image folders, either by modifying include_path in php.ini, or modifying it in the script:
ini_set('include_path', '/new/include/path');
Then use the "use_include_path" option in fopen.
Since you're looking across all the php folders, be sure to sanity check the image file name.
The problem may be because $imgPng = imageCreateFromPng($file); cannot find the file. You need to specify the path to your image $d. $file. Check the comments in code below.
<?php
$file = 'testimage.png';
$dir = array($_SERVER['DOCUMENT_ROOT'] . "/folderA/", $_SERVER['DOCUMENT_ROOT'] . "/folderB/");
foreach ($dir as $d) {
if (file_exists($d . $file)) {
$file = $file;
//i don't know the purpose of this but i think you want to do $file = $d . $file
}
}
//$imgPng = imageCreateFromPng($file); //can't find the image, should be
$imgPng = imageCreateFromPng($d . $file);
header("Content-type: image/png");
imagePng($imgPng);
?>
<?php
$file = 'testimage.png';
$dir = [
$_SERVER['DOCUMENT_ROOT'] . "/pathA/",
$_SERVER['DOCUMENT_ROOT'] . "/pathB/"];
foreach( $dir as $d )
{
if( file_exists( $d . $file ))
{
//set image if found in the directories
$image = $d . $file;
}
else
{
//is not found in directories
$image = null;
}
}
$img = imagecreatefrompng($image);
header("Content-type: image/png");
imagepng($img);
imagedestroy();
?>

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!

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

php check file name exist, rename the file

How do I check if file name exists, rename the file?
for example, I upload a image 1086_002.jpg if the file exists, rename the file as 1086_0021.jpg and save, if 1086_0021.jpg is exist, rename 1086_00211.jpg and save , if 1086_00211.jpg is exist, rename 1086_002111.jpg and save...
Here is my code, it only can do if 1086_002.jpg exist, rename the file as 1086_0021.jpg, maybe should do a foreach, but how?
//$fullpath = 'images/1086_002.jpg';
if(file_exists($fullpath)) {
$newpieces = explode(".", $fullpath);
$frontpath = str_replace('.'.end($newpieces),'',$fullpath);
$newpath = $frontpath.'1.'.end($newpieces);
}
file_put_contents($newpath, file_get_contents($_POST['upload']));
Try something like:
$fullpath = 'images/1086_002.jpg';
$additional = '1';
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/'
. $info['filename'] . $additional
. '.' . $info['extension'];
}
Why not just append a timestamp onto the filename? Then you won't have to worry about arbitrarily long filenames for files which have been uploaded many times.
I hope this helps
$fullPath = "images/1086_002.jpg" ;
$fileInfo = pathinfo($fullPath);
list($prifix, $surfix) = explode("_",$fileInfo['filename']);
$x = intval($surfix);
$newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT) . $fileInfo['extension'];
while(file_exists($newFile)) {
$x++;
$newFile = $fileInfo['dirname'] . DIRECTORY_SEPARATOR . $prifix. "_" . str_pad($x, 2,"0",STR_PAD_LEFT) . $fileInfo['extension'];
}
file_put_contents($newFile, file_get_contents($_POST['upload']));
I hope this Helps
Thanks
:)
I feel this would be better. It will help keep track of how many times a file with the same name was uploaded. It works in the same way like Windows OS renames files if it finds one with the same name.
How it works: If the media directory has a file named 002.jpg and you try to upload a file with the same name, it will be saved as 002(1).jpg Another attempt to upload the same file will save the new file as 002(2).jpg
Hope it helps.
$uploaded_filename_with_ext = $_FILES['uploaded_image']['name'];
$fullpath = 'media/' . $uploaded_filename_with_ext;
$file_info = pathinfo($fullpath);
$uploaded_filename = $file_info['filename'];
$count = 1;
while (file_exists($fullpath)) {
$info = pathinfo($fullpath);
$fullpath = $info['dirname'] . '/' . $uploaded_filename
. '(' . $count++ . ')'
. '.' . $info['extension'];
}
$image->save($fullpath);
You can change your if statement to a while loop:
$newpath = $fullpath;
while(file_exists($newpath)) {
$newpieces = explode(".", $fullpath);
$frontpath = str_replace('.'.end($newpieces),'',$fullpath);
$newpath = $frontpath.'1.'.end($newpieces);
}
file_put_contents($newpath, file_get_contents($_POST['upload']));

Categories