I have a folder containing several photos all in .jpg
The name they should all have is STYLE_COLOR-n.jpg for example K14700_7132-6.jpg because I made a script that deletes all the photos greater than -6.jpg.
My problem is that I have photos that are badly renamed, i.e. they have an underscore at the end instead of the dash like :
K14700_7132_6.jpg
Some also have a dash on both like this:
K14700-7132_6.jpg
And so my delete script doesn't work if the pictures don't all have the same rename...
Is it possible to automatically replace all the dashes and underscores that are bad to have this format on all my folder STYLE_COLOR-n.jpg?
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file)
{
if (!in_array($file,array(".","..")))
{
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
$underscore = explode("_", $filename);
// echo $underscore[0]."<br>"; //KA0710
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6)
{
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
}
else
{
}
}
}
echo "Deleted photos !";
?>
Sure, this is the part you'll add to that code:
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
Note - this will permanently rename files (that need it) so BEFORE you run this in production, please test for the old/new rename arguments just to be safe!
Here is the whole enchilada
<?php
$dir = 'C:/wamp64/www/divers/photos/';
$allFiles = scandir($dir);
foreach($allFiles as $file) {
if (!in_array($file,array(".",".."))) {
$file = $dir.$file;
$filename = basename( $file ); //KA0710_7250-1.jpg
// first fix the format
$parts = preg_split("/[-_]+/", $filename);
$newfilename = strtoupper($parts[0].'_'.$parts[1]).'-'.$parts[2];
if ($newfilename !== $filename) {
rename($dir.$filename, $dir.$newfilename); // test this!
$filename = $newfilename;
}
$underscore = explode("_", $filename);
$endstring = end($underscore);
// echo $endstring."<br>"; //7250-1.jpg
$underscore2 = explode("-", $endstring);
// echo $underscore2[1]."<br>"; //1.jpg
if ($underscore2[1] > 6) {
unlink("$dir$filename");
echo 'File ' . $filename . ' has been deleted'."<br>";
} else {
}
}
}
echo "Deleted photos !";
?>
Related
I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.
I am using WordPress. I have an image folder like mytheme/images/myimages.
I want to retrieve all the images name from the folder myimages
Please advice me, how can I get images name.
try this
$directory = "mytheme/images/myimages";
$images = glob($directory . "/*.jpg");
foreach($images as $image)
{
echo $image;
}
you can do it simply with PHP opendir function.
example:
$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
echo '<img src="pictures/'.$file.'" border="0" />';
}
}
When you want to get all image from folder then use glob() built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
If you do not want to check image type then you can use this code also
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
}
for more information
PHP Manual
Here is my some code
$dir = '/Images';
$ImagesA = Get_ImagesToFolder($dir);
print_r($ImagesA);
function Get_ImagesToFolder($dir){
$ImagesArray = [];
$file_display = [ 'jpg', 'jpeg', 'png', 'gif' ];
if (file_exists($dir) == false) {
return ["Directory \'', $dir, '\' not found!"];
}
else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = pathinfo($file, PATHINFO_EXTENSION);
if (in_array($file_type, $file_display) == true) {
$ImagesArray[] = $file;
}
}
return $ImagesArray;
}
}
This answer is specific for WordPress:
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$media_dir = $base_dir . 'yourfolder/images/';
$media_url = $hase_url . 'yourfolder/images/';
$image_paths = glob( $media_dir . '*.jpg' );
$image_names = array();
$image_urls = array();
foreach ( $image_paths as $image ) {
$image_names[] = str_replace( $media_dir, '', $image );
$image_urls[] = str_replace( $media_dir, $media_url, $image );
}
// --- You now have:
// $image_paths ... list of absolute file paths
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
// $image_urls ... list of absolute file URLs
// e.g. http://example.com/wp-content/uploads/yourfolder/images/sample.jpg
// $image_names ... list of filenames only
// e.g. sample.jpg
Here are some other settings that will give you images from other places than the child theme. Just replace the first 2 lines in above code with the version you need:
From Uploads directory:
// e.g. /path/to/wordpress/wp-content/uploads/yourfolder/images/sample.jpg
$upload_path = wp_upload_dir();
$base_dir = trailingslashit( $upload_path['basedir'] );
$base_url = trailingslashit( $upload_path['baseurl'] );
From Parent-Theme
// e.g. /path/to/wordpress/wp-content/themes/parent-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_template_directory() );
$base_url = trailingslashit( get_template_directory_uri() );
From Child-Theme
// e.g. /path/to/wordpress/wp-content/themes/child-theme/yourfolder/images/sample.jpg
$base_dir = trailingslashit( get_stylesheet_directory() );
$base_url = trailingslashit( get_stylesheet_directory_uri() );
$dir = "mytheme/images/myimages";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);
Very fast because you only scan the needed directory.
//path to the directory to search/scan
$directory = "";
//echo "$directory"
//get all files in a directory. If any specific extension needed just have to put the .extension
//$local = glob($directory . "*");
$local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
//print each file name
echo "<ul>";
foreach($local as $item)
{
echo '<li>'.$item.'</li>';
}
echo "</ul>";
Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:
$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);
if ($handle = opendir('/path/to/folder')) {
while (false !== ($entry = readdir($handle))) {
$files[] = $entry;
}
$images=preg_grep('/\.jpg$/i', $files);
foreach($images as $image)
{
echo $image;
}
closedir($handle);
}
<?php
$galleryDir = 'gallery/';
foreach(glob("$galleryDir{*.jpg,*.gif,*.png,*.tif,*.jpeg}", GLOB_BRACE) as $photo)
{echo "\n" ;echo "<img style=\"padding:7px\" class=\"uk-card uk-card-default uk-card-hover uk-card-body\" src=\"$photo\">"; echo "";}?>
UIkit php folder gallery
https://webshelf.eu/en/php-folder-gallery/
// Store your file destination to a variable
$fileDirectory = "folder1/folder2/../imagefolder/";
// glob function will create a array of all provided file type form the specified directory
$imagesFiles = glob($fileDirectory."*.{jpg,jpeg,png,gif,svg,bmp,webp}",GLOB_BRACE);
// Use your favorite loop to display
foreach($imagesFiles as $image) {
echo '<img src="'.$image.'" /><br />';
}
get all the images from a folder in php without database
$url='https://demo.com/Images/sliderimages/';
$dir = "Images/sliderimages/";
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
$data=array();
if (file_exists($dir) == false) {
$rss[]=array('imagePathName' =>"Directory '$dir' not found!");
$msg=array('error'=>1,'images'=>$rss);
echo json_encode($msg);
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
#$file_type = strtolower(end(explode('.', $file)));
// $file_type1 = pathinfo($file);
// $file_type= $file_type1['extension'];
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
$data[]=array('imageName'=>$url.$file);
}
}
if(!empty($data)){
$msg=array('error'=>0,'images'=>$data);
echo json_encode($msg);
}else{
$rees[]=array('imagePathName' => 'No Image Found!');
$msg=array('error'=>2,'images'=>$rees);
echo json_encode($msg);
}
}
You can simply show your actual image directory(less secure). By just 2 line of code.
$dir = base_url()."photos/";
echo"Photo Directory";
I'm trying to rename the file name of an image when it's uploaded if it exists, say if my file name is test.jpg and it already exists I want to rename it as test1.jpg and then test2.jpg and so on. With the code I've written its changing my file name like so test1.jpg and then test12.jpg any advice on fixing this would be great thank!
PHP
$name = $_FILES['picture']['name'];
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$actual_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Here's a minor modification that I think should do what you want:
$actual_name = pathinfo($name,PATHINFO_FILENAME);
$original_name = $actual_name;
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
while(file_exists('tmp/'.$actual_name.".".$extension))
{
$actual_name = (string)$original_name.$i;
$name = $actual_name.".".$extension;
$i++;
}
Inspired from #Jason answer, i created a function which i deemed shorter and more readable filename format.
function newName($path, $filename) {
$res = "$path/$filename";
if (!file_exists($res)) return $res;
$fnameNoExt = pathinfo($filename,PATHINFO_FILENAME);
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Example:
$name = "foo.bar";
$path = 'C:/Users/hp/Desktop/ikreports';
for ($i=1; $i<=10; $i++) {
$newName = newName($path, $name);
file_put_contents($newName, 'asdf');
}
New version (2022):
function newName2($fullpath) {
$path = dirname($fullpath);
if (!file_exists($fullpath)) return $fullpath;
$fnameNoExt = pathinfo($fullpath,PATHINFO_FILENAME);
$ext = pathinfo($fullpath, PATHINFO_EXTENSION);
$i = 1;
while(file_exists("$path/$fnameNoExt ($i).$ext")) $i++;
return "$path/$fnameNoExt ($i).$ext";
}
Usage:
for ($i=1; $i<=10; $i++) {
$newName = newName2($fullpath);
file_put_contents($newName, 'asdf');
}
There are several ways for renaming image in PHP before uploading to the server.
appending timestamp, unique id, image dimensions plus random number etc.You can see them all here
First, Check if the image filename exists in the hosted image folder otherwise upload it. The while loop checks if the image file name exists and appends a unique id as shown below ...
function rename_appending_unique_id($source, $tempfile){
$target_path ='uploads-unique-id/'.$source;
while(file_exists($target_path)){
$fileName = uniqid().'-'.$source;
$target_path = ('uploads-unique-id/'.$fileName);
}
move_uploaded_file($tempfile, $target_path);
}
if(isset($_FILES['upload']['name'])){
$sourcefile= $_FILES['upload']['name'];
tempfile= $_FILES['upload']['tmp_name'];
rename_appending_unique_id($sourcefile, $tempfile);
}
Check more image renaming tactics
I checked SO and found a nice C# answer here, so I ported it for PHP:
['extension' => $extension] = pathinfo($filePath);
$count = 0;
while (file_exists($filePath) === true) {
if ($count === 0) {
$filePath = str_replace($extension, '[' . ++$count . ']' . ".$extension", $filePath);
} else {
$filePath = str_replace("[$count].$extension", '[' . ++$count . ']' . ".$extension", $filePath);
}
}
This question already has answers here:
Getting the names of all files in a directory with PHP
(15 answers)
Closed 6 months ago.
I have the code below that lists all the images in a folder, the problem is that it finds some files ( a . and a ..) that I am not sure what they are so I am not sure how to prevent them from showing up. I am on a windows XP machine, any help would be great, thanks.
Errors: Warning: rename(images/.,images/.) [function.rename]: No error
in C:\wamp\www\Testing\listPhotosA.php on line 14
Warning: rename(images/..,images/..) [function.rename]: No error in
C:\wamp\www\Testing\listPhotosA.php on line 14
Code:
<?php
define('IMAGEPATH', 'images/');
if (is_dir(IMAGEPATH)){
$handle = opendir(IMAGEPATH);
}
else{
echo 'No image directory';
}
$directoryfiles = array();
while (($file = readdir($handle)) !== false) {
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
foreach($directoryfiles as $directoryfile){
if(strlen($directoryfile) > 3){
echo '<img src="' . IMAGEPATH . $directoryfile . '" alt="' . $directoryfile . '" /> <br>';
}
}
closedir($handle); ?>
I like PHP's glob function.
foreach(glob(IMAGEPATH.'*') as $filename){
echo basename($filename) . "\n";
}
glob() is case sensitive and the wildcard * will return all files, so I specified the extension here so you don't have to do the filtering work
$d = 'path/to/images/';
foreach(glob($d.'*.{jpg,JPG,jpeg,JPEG,png,PNG}',GLOB_BRACE) as $file){
$imag[] = basename($file);
}
Use glob function.
<?php
define('IMAGEPATH', 'images/');
foreach(glob(IMAGEPATH.'*') as $filename){
$imag[] = basename($filename);
}
print_r($imag);
?>
You got all images in array format
To get all jpg images in all dirs and subdirs inside a folder:
function getAllDirs($directory, $directory_seperator) {
$dirs = array_map(function ($item) use ($directory_seperator) {
return $item . $directory_seperator;
}, array_filter(glob($directory . '*'), 'is_dir'));
foreach ($dirs AS $dir) {
$dirs = array_merge($dirs, getAllDirs($dir, $directory_seperator));
}
return $dirs;
}
function getAllImgs($directory) {
$resizedFilePath = array();
foreach ($directory AS $dir) {
foreach (glob($dir . '*.jpg') as $filename) {
array_push($resizedFilePath, $filename);
}
}
return $resizedFilePath;
}
$directory = "C:/xampp/htdocs/images/";
$directory_seperator = "/";
$allimages = getAllImgs(getAllDirs($directory, $directory_seperator));
Using balphp's scan_dir function:
https://github.com/balupton/balphp/blob/765ee3cfc4814ab05bf3b5512b62b8b984fe0369/lib/core/functions/_scan_dir.funcs.php
scan_dir($dirPath, array('pattern'=>'image'));
Will return an array of all files that are images in that path and all subdirectories, using a $path => $filename structure. To turn off scanning subdirectories, set the recurse option to false
Please use the following code to read images from the folder.
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.DS.'images'.DS.$imageFolderName.DS;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
}
Please click here for detailed explanation.
http://www.pearlbells.co.uk/code-snippets/read-images-folder-php/
You can use OPP oriented DirectoryIterator class.
foreach (new DirectoryIterator(IMAGEPATH) as $fileInfo) {
// Removing dots
if($fileInfo->isDot()) {
continue;
}
// You have all necessary data in $fileInfo
echo $fileInfo->getFilename() . "<br>\n";
}
while (($file = readdir($handle)) !== false) {
if (
($file == '.')||
($file == '..')
) {
continue;
}
$newfile = str_replace(' ', '_', $file);
rename(IMAGEPATH . $file, IMAGEPATH . $newfile);
$directoryfiles[] = $newfile;
}
I need to create a loop through all files in subdirectories. Can you please help me struct my code like this:
$main = "MainDirectory";
loop through sub-directories {
loop through filels in each sub-directory {
do something with each file
}
};
Use RecursiveDirectoryIterator in conjunction with RecursiveIteratorIterator.
$di = new RecursiveDirectoryIterator('path/to/directory');
foreach (new RecursiveIteratorIterator($di) as $filename => $file) {
echo $filename . ' - ' . $file->getSize() . ' bytes <br/>';
}
You need to add the path to your recursive call.
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..') {
echo "Found Folder $newPath<br>";
readDirs($newPath);
}
else{
echo ' Found File or .-dir '.$item.'<br>';
}
}
}
$path = "/";
echo "$path<br>";
readDirs($path);
You probably want to use a recursive function for this, in case your sub directories have sub-sub directories
$main = "MainDirectory";
function readDirs($main){
$dirHandle = opendir($main);
while($file = readdir($dirHandle)){
if(is_dir($main . $file) && $file != '.' && $file != '..'){
readDirs($file);
}
else{
//do stuff
}
}
}
didn't test the code, but this should be close to what you want.
I like glob with it's wildcards :
foreach (glob("*/*.txt") as $filename) {
echo "$filename\n";
}
Details and more complex scenarios.
But if You have a complex folders structure RecursiveDirectoryIterator is definitively the solution.
Come on, first try it yourself!
What you'll need:
scandir()
is_dir()
and of course foreach
http://php.net/manual/en/function.is-dir.php
http://php.net/manual/en/function.scandir.php
Another solution to read with sub-directories and sub-files (set correct foldername):
<?php
$path = realpath('samplefolder/yorfolder');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename <br/>";
}
?>
Minor modification on what John Marty posted, if we can safely eliminate any items that are named . or ..
function readDirs($path){
$dirHandle = opendir($path);
while($item = readdir($dirHandle)) {
$newPath = $path."/".$item;
if (($item == '.') || ($item == '..')) {
continue;
}
if (is_dir($newPath)) {
pretty_echo('Found Folder '.$newPath);
readDirs($newPath);
} else {
pretty_echo('Found File: '.$item);
}
}
}
function pretty_echo($text = '')
{
echo $text;
if (PHP_OS == 'Linux') {
echo "\r\n";
}
else {
echo "</br>";
}
}
<?php
ini_set('max_execution_time', 300); // increase the execution time of the file (in case the number of files or file size is more).
class renameNewFile {
static function copyToNewFolder() { // copies the file from one location to another.
$main = 'C:\xampp\htdocs\practice\demo'; // Source folder (inside this folder subfolders and inside each subfolder files are present.)
$main1 = 'C:\xampp\htdocs\practice\demomainfolder'; // Destination Folder
$dirHandle = opendir($main); // Open the source folder
while ($file = readdir($dirHandle)) { // Read what's there inside the source folder
if (basename($file) != '.' && basename($file) != '..') { // Ignore if the folder name is '.' or '..'
$folderhandle = opendir($main . '\\' . $file); // Open the Sub Folders inside the Main Folder
while ($text = readdir($folderhandle)) {
if (basename($text) != '.' && basename($text) != '..') { // Ignore if the folder name is '.' or '..'
$filepath = $main . '\\' . $file . '\\' . $text;
if (!copy($filepath, $main1 . '\\' . $text)) // Copy the files present inside the subfolders to destination folder
echo "Copy failed";
else {
$fh = fopen($main1 . '\\' . 'log.txt', 'a'); // Write a log file to show the details of files copied.
$text1 = str_replace(' ', '_', $text);
$data = $file . ',' . strtolower($text1) . "\r\n";
fwrite($fh, $data);
echo $text . " is copied <br>";
}
}
}
}
}
}
static function renameNewFileInFolder() { //Renames the files into desired name
$main1 = 'C:\xampp\htdocs\practice\demomainfolder';
$dirHandle = opendir($main1);
while ($file = readdir($dirHandle)) {
if (basename($file) != '.' && basename($file) != '..') {
$filepath = $main1 . '\\' . $file;
$text1 = strtolower($filepath);
rename($filepath, $text1);
$text2 = str_replace(' ', '_', $text1);
if (rename($filepath, $text2))
echo $filepath . " is renamed to " . $text2 . '<br/>';
}
}
}
}
renameNewFile::copyToNewFolder();
renameNewFile::renameNewFileInFolder();
?>
$allFiles = [];
public function dirIterator($dirName)
{
$whatsInsideDir = scandir($dirName);
foreach ($whatsInsideDir as $fileOrDir) {
if (is_dir($fileOrDir)) {
dirIterator($fileOrDir);
}
$allFiles.push($fileOrDir);
}
return $allFiles;
}