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;
Related
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);
}
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path
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 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
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).