How to move files to another folder in php - php

I have 4 csv files in "files" folder & I want to move these files with content to another folder (i.e. backups),Files are given below.
abc.csv
abc1.csv
abc2.csv
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
$rename_file = $file.'_'.$date;
move_uploaded_file($rename_file, "$destination");
}

Since you are not uploading any files, try rename() function instead.
$Ignore = array(".","..","Thumbs.db");
$OriginalFileRoot = "files";
$OriginalFiles = scandir($OriginalFileRoot);
$DestinationRoot = "backups";
# Check to see if "backups" exists
if(!is_dir($DestinationRoot)){
mkdir($DestinationRoot,0777,true);
}
$Date = date('Y-m-d');
foreach($OriginalFiles as $OriginalFile){
if(!in_array($OriginalFile,$Ignore)){
$FileExt = pathinfo($OriginalFileRoot."\\".$OriginalFile, PATHINFO_EXTENSION); // Get the file extension
$Filename = basename($OriginalFile, ".".$FileExt); // Get the filename
$DestinationFile = $DestinationRoot."\\".$Filename.'_'.$Date.".".$FileExt; // Create the destination filename
rename($OriginalFileRoot."\\".$OriginalFile, $DestinationFile); // rename the file
}
}

The function move_uploaded_file is relevant for uploading files, not for other things.
To move file in the filesystem you should use the rename function:
$files = scandir('files');
$destination = 'backups/';
$date = date('Y-m-d');
foreach($files as $file){
if (!is_file($file)) {
continue;
}
$rename_file = $destination.$file.'_'.$date;
rename($file, $rename_file);
}

Related

How to increment unique filename based on directory array

I'm creating an upload form that when uploading files will check to see if a file with the same name already exists in the directory. If a file with the same name is found, the script should increment the file by appending the file name with a number such as test1.txt test2.txt and so on until a match is not found. This is what I have come up with so far but wanted to see if there is a different approach I should take.
Also note, my filenames are already cleaned before they enter this part of the script so my filename and extension functions are simplified.
function filename($file){
return substr($file,0,strrpos($file,'.'));
}
function extension($file){
return strtolower(substr(strrchr($file,'.'),1));
}
$new_file = 'test.txt';
$dir = 'files';
$files = scandir($dir);
$exclude = array('.','..');
foreach($files as $file){
if(!in_array($file,$exclude)){
$file_array[] = $file;
}
}
$i = 1;
while(in_array($new_file,$file_array)){
$filename = filename($new_file);
$extension = extension($new_file);
if($i>1){
$num = strlen($filename);
$filename = substr($filename,0,-1);
$new_file = $filename.$i.'.'.$extension;
} else {
$new_file = $filename.$i.'.'.$extension;
}
echo $new_file.'<br>';
echo $i.'<br>';
$i++;
}
echo $new_file;

rename all the files in a folder

i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.
i have an input field for 'name' i want to use that name, add a uniqid and rename all the files.
here's the code that i am using:
<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {
$newName = uniqid().$name;
rename($directory.$file, $directory.$newName);
}}}
?>
besides, do i really need to _Post the $name variable?
P.S. i want to rename all the files and then copy them to another folder.
You don't need to POST name
glob is return you every files in folder with path // example /basic_images/test.jpg
then you just do foreach to loop over files, and update its name.
$path = "../basic_images/";
$directory = glob($path,"*.*");
foreach($directory as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$newName = uniqid().$ext;
rename($file, $path.$newName);
}
read more about glob : http://php.net/manual/en/function.glob.php
so, i finally solved the problem. now, instead of renaming the original files and then copying them to another folder, i just create new copies of the files with new names.
This is the code final code that works for me:
if(isset($_POST['submit'])){
$path = "../posts_images/";
$files = glob("../basic_images/*.*");
foreach($files as $file){
$ext = pathinfo($file, PATHINFO_EXTENSION);
$name = $_POST['new_name'];
$pic = uniqid().$name;
$newName = $pic.'.'.$ext;
copy($file, $path.$newName);
}}
it is important to use $pic.'.'.$ext because without it the new files don't have any extension.

Read only pdf files and get the filename of that pdf files in a directory

I need to read only pdf files in a directory and then read the filename of every files then I will use the filename to rename some txt files. I have tried using only eregi function. but it seems cannot read all I need. how to read them well?
here's my code :
$savePath ='D:/dir/';
$dir = opendir($savePath);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$read = strtok ($filename,"."); //get the filenames
//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
$testfile = "$read.txt";
$file = fopen($testfile,"r") or die ('cannot open file');
if (filesize($testfile)==0){}
else{
$text = fread($file,55024);
fclose($file);
echo "</br>"; echo "</br>";
}
}
More elegant:
foreach (glob("D:/dir/*.pdf") as $filename) {
// do something with $filename
}
To get the filename only:
foreach (glob("D:/dir/*.pdf") as $filename) {
$filename = basename($filename);
// do something with $filename
}
You can do this by filter file type.. following is sample code.
<?php
// directory path can be either absolute or relative
$dirPath = '.';
// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {
// keep reading the directory entries 'til the end
$i=0;
while (false !== ($file = readdir($handle))) {
$i++;
// just skip the reference to current and parent directory
if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){
if (is_dir("$dirPath/$file")) {
// found a directory, do something with it?
echo " [$file]<br>";
} else {
// found an ordinary file
echo $i."- $file<br>";
}
}
}
// ALWAYS remember to close what you opened
closedir($handle);
}
?>
Above is demonstrating for file type related to images you can do the same for .PDF files.
Better explained here

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

Code to zip uploaded files fails to delete temporary files

I guys, i'm writting code to upload file, zip them and delete tmp file.
But when i use unlink function, it do not remove all file, someone can explain to me why ?
Concerned php code :
$zip = new ZipArchive();
$target_path = 'img/products/';
$zip->open($target_path.$id_insert.'.zip', ZIPARCHIVE::CREATE);
$img_count = $_POST['count_file'];
for ($i = 1; $i <= $img_count; $i++){
$temp = 'img'.$i;
$file = $i.'-'.$id_insert.'-'.$_FILES[$temp]['name'];
$path = $target_path.basename($file);
if(move_uploaded_file($_FILES[$temp]['tmp_name'], $path)) {
$zip->addFile($path, basename($file));
$files_to_delete[] = $path;
}
}
$zip->close();
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
foreach($files_to_delete AS $file){
//unlink(dirname(__FILE__).'/'.$path);
}
In this block you should replace $path with $file since that's what you're foreaching them as. You get the error because after you unlink $path the first time, the file at $path is unlinked, but every other iteration of it tries to delete the same file (which is the last one assigned to the $path variable).

Categories