Bulk Rename Files in a Folder - PHP - php

I have 1000 images in a Folder, which has SKU# word in all the images. For examples
WV1716BNSKU#.zoom.1.jpg
WV1716BLSKU#.zoom.3.jpg
what i need to do is read all the filenames and rename it to the following
WV1716BN.zoom.1.jpg
WV1716BL.zoom.3.jpg
So remove SKU# from filename, is it possible in PHP to do bulk renaming ?

Yeah, just open the directory and create a loop to access all images and rename them, like:
<?php
if ($handle = opendir('./path/to/files')) {
while (false !== ($fileName = readdir($handle))) {
if($fileName != '.' && $fileName != '..') {
$newName = str_replace("SKU#","",$fileName);
rename('./path/to/files/'.$fileName, './path/to/files'.$newName);
}
}
closedir($handle);
}
?>
References:
http://php.net/manual/en/function.rename.php
http://php.net/manual/en/function.readdir.php
http://php.net/manual/en/function.str-replace.php

piece of cake:
foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
rename ($f, str_replace("SKU#", "", $f));
(or $dir/*.jpg if number doesn't matter)

The steps to completing this is pretty simple:
iterate over each file using fopen, readdir
for each file parse the file name into segments
copy the old file into a new directly called old (sanity reasons)
rename the root file top the new name.
A small example:
if ($handle = opendir('/path/to/images'))
{
/* Create a new directory for sanity reasons*/
if(is_directory('/path/to/images/backup'))
{
mkdir('/path/to/images/backup');
}
/*Iterate the files*/
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
if(!strstr($file,"#SKU"))
{
continue; //Skip as it does not contain #SKU
}
copy("/path/to/images/" . $file,"/path/to/images/backup/" . $file);
/*Remove the #SKU*/
$newf = str_replace("#SKU","",$file);
/*Rename the old file accordingly*/
rename("/path/to/images/" . $file,"/path/to/images/" . $newf);
}
}
/*Close the handle*/
closedir($handle);
}

Well, using iterators:
class SKUFilterIterator extends FilterIterator {
public function accept() {
if (!parent::current()->isFile()) return false;
$name = parent::current()->getFilename();
return strpos($name, 'SKU#') !== false;
}
}
$it = new SkuFilterIterator(
new DirectoryIterator('path/to/files')
);
foreach ($it as $file) {
$newName = str_replace('SKU#', '', $file->getPathname());
rename($file->getPathname(), $newName);
}
The FilterIterator basically filters out all non-files, and files without the SKU# in them. Then all you do is iterate, declare a new name, and rename the file...
Or in 5.3+ using the new GlobIterator:
$it = new GlobIterator('path/to/files/*SKU#*');
foreach ($it as $file) {
if (!$file->isFile()) continue; //Only rename files
$newName = str_replace('SKU#', '', $file->getPathname());
rename($file->getPathname(), $newName);
}

You can also use this sample:
$directory = 'img';
$gallery = scandir($directory);
$gallery = preg_grep ('/\.jpg$/i', $gallery);
// print_r($gallery);
foreach ($gallery as $k2 => $v2) {
if (exif_imagetype($directory."/".$v2) == IMAGETYPE_JPEG) {
rename($directory.'/'.$v2, $directory.'/'.str_replace("#SKU","",$v2));
}
}

$curDir = "/path/to/unprocessed/files";
$newdir = "/path/to/processed/files";
if ($handle = opendir($curDir))
{
//make the new directory if it does not exist
if(!is_dir($newdir))
{
mkdir($newdir);
}
//Iterate the files
while ($file = readdir($handle))
{
// invalid files check (directories or files with no extentions)
if($file != "." && $file != "..")
{
//copy
copy($curDir."/".$file, $newdir."/".$file);
$newName = str_replace("SKU#","",$file);
//rename
rename($newdir."/".$file, $newdir."/".$newName.".jpg");
}
}
closedir($handle);
}

Related

PHP Directory, subdirectory and file Listing default sort order

i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);

Move and rename folders php

I'm working with a script where i want to move folders to another directory,and give the folders new name.
I think i need to explode a string? But i don't get it to work properly.
Example i want the folder with original name: 351437-367628 and to have new name: from start to the hyphen.
I'm moving the folder by the glob and rename function.
<?php
if ($handle = opendir('folders')) {
while (false !== ($fileName = readdir($handle))) {
$newName = str_replace("-#","",$fileName);
rename($fileName, $newName);
}
closedir($handle);
}
?>
You can use explode() function as
$fileName = '351437-367628';
$newNametemp = explode("-",$fileName);
if(is_array($newNametemp)){
$newName = $newNametemp[0];
print_r($newName); // will return 351437,i.e. new name from start to hyphen
rename($fileName, $newName);
}
To get all directories
$dir = new DirectoryIterator('path');
foreach ($dir as $fileInfo) {
if ($fileInfo->isDir() && !$fileInfo->isDot()) {
$fileName = $fileInfo->getFilename();
$newNametemp = explode("-",$fileName);
if(is_array($newNametemp)){
$newName = $newNametemp[0];
print_r($newName);
rename($fileName, $newName);
}
}
}
if you are using a lower version of PHP try
if ($handle = opendir('path')) {
while (false !== ($fileName = readdir($handle))) {
if(is_dir($fileName) && ($fileName != '..' && $fileName != '.')){
$newNametemp = explode("_",$fileName);
if(is_array($newNametemp)){
$newName = $newNametemp[0];
print_r($newName);
echo "<br/>";
rename($fileName, $newName);
}
}
}
closedir($handle);
}

Recursivly get all files in a directory, and sub directories by extension

I was looking at RecursiveDirectoryIterator and glob to say
"return me a list of files (in an array) based on the extension (for example) .less. Oh and look in all child, grandchild and so on and so forth, excluding . and .. until you find all files matching."
But I am not sure the best approach to create a recursive function that keeps going well beyond the grand child.
What I have is a mess, its worked for two years - but now I need to refactor and change it up:
public function get_directory_of_files($path, $filename, $extension) {
if (!is_dir($path)) {
throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if (file_exists($filename)) {
$handler = opendir($path);
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
$this->package_files [] = $file;
$count = count($this->package_files);
for ($i = 0; $i < $count; $i++) {
if (substr(strrchr($this->package_files [$i], '.'), 1) == $extension) {
if ($this->package_files [$i] == $filename) {
$this->files_got_back = $this->package_files [$i];
}
}
}
}
}
}
return $this->_files_got_back;
}
This requires a file name to be passed in and thats not really my thing to do any more. So how can I re-write this function to do the above "pseudo code"
This function recursively finds files with a matching ending string
function getDirectoryContents($directory, $extension)
{
$extension = strtolower($extension);
$files = array();
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
while($it->valid())
{
if (!$it->isDot() && endsWith(strtolower($it->key()), $extension))
{
array_push($files, $it->key());
}
$it->next();
}
return $files;
}
function endsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
Used like so
print_r(getDirectoryContents('folder/', '.php'));
It converts the extension to lowercase to compare against
Take a look at this code:
<?php
class ex{
private function get_files_array($path,$ext, &$results){ //&to ensure it's a reference... but in php obj are passed by ref.
if (!is_dir($path)) {
//throw new AisisCore_FileHandling_FileException("Could not find said path: " . $path);
}
if ($dir = opendir($path)) {
$extLength = strlen($ext);
while (false !== ($file = readdir($dir))) {
if ($file != '.' && $file != '..'){
if (is_file($path.'/'.$file) && substr($file,-$extLength) == $ext){
$results[] = $path . '/' . $file; //it's a file and the correct extension
}
elseif (is_dir($path . '/'. $file)){
$this->get_files_array($path.'/'.$file, $ext, $results); //it's a dir
}
}
}
}else{
//unable to open dir
}
}
public function get_files_deep($path,$ext){
$results = array();
$this->get_files_array($path,$ext,$results);
return $results;
}
}
$ex = new ex();
var_dump($ex->get_files_deep('_some_path','.less'));
?>
It will retrieve all the files with the matching extension in the path and it's sub directories.
I hope it's what you need.

Rename all files in a directory with numbers

I was wondering if anyone could help me write a PHP script for me that renames all the files in a directory in a sequence.
So...
DSC_10342.JPG -> 1.JPG
DSC_10343.JPG -> 2.JPG
DSC_10344.JPG -> 3.JPG
and so on.
Here's my version:
// open the current directory (change this to modify where you're looking)
$dir = opendir('.');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
// if the extension is '.jpg'
if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'jpg')
{
// do the rename based on the current iteration
$newName = $i . '.jpg';
rename($file, $newName);
// increase for the next loop
$i++;
}
}
// close the directory handle
closedir($dir);
Use rename to rename the files. You can use this handy script to loop through all files in a directory:
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Then it's just a matter of looking at the filenames ($file) and figuring out what number to give them. If you need more help than that, just tell me and I'll give more details.
Try this:
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
if ($file != "." && $file != "..") {
rename($directory."/".$file, $directory."/".$index.".JPG");
$index++;
}
}
closedir($handler);
Using someone's snippet it would look like this:
<?php
$path = '.';
$i = 1;
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != ".." && is_file($path.'/'.$file)) {
$oldname = $path.'/'.$file;
$path_info = pathinfo($oldname);
rename($oldname, $path.'/'.($i++).'.'.$path_info['extension']);
}
}
closedir($handle);
}
?>
It will rename files with all extensions and skip directories that may be inside your directory.

Sort and display directory list alphabetically using opendir() in php

php noob here - I've cobbled together this script to display a list of images from a folder with opendir, but I can't work out how (or where) to sort the array alphabetically
<?php
// opens images folder
if ($handle = opendir('Images')) {
while (false !== ($file = readdir($handle))) {
// strips files extensions
$crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");
$newstring = str_replace($crap, " ", $file );
//asort($file, SORT_NUMERIC); - doesnt work :(
// hides folders, writes out ul of images and thumbnails from two folders
if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
echo "<li><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </li>\n";}
}
closedir($handle);
}
?>
Any advice or pointers would be much appreciated!
You need to read your files into an array first before you can sort them. How about this?
<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('Images')) {
while (false !== ($file = readdir($handle))) {
// strips files extensions
$crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");
$newstring = str_replace($crap, " ", $file );
//asort($file, SORT_NUMERIC); - doesnt work :(
// hides folders, writes out ul of images and thumbnails from two folders
if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
$dirFiles[] = $file;
}
}
closedir($handle);
}
sort($dirFiles);
foreach($dirFiles as $file)
{
echo "<li><img src=\"Images/Thumbnails/$file\" alt=\"$newstring\" width=\"300\" </li>\n";
}
?>
Edit: This isn't related to what you're asking, but you could get a more generic handling of file extensions with the pathinfo() function too. You wouldn't need a hard-coded array of extensions then, you could remove any extension.
Using opendir()
opendir() does not allow the list to be sorted. You'll have to perform the sorting manually. For this, add all the filenames to an array first and sort them with sort():
$path = "/path/to/file";
if ($handle = opendir($path)) {
$files = array();
while ($files[] = readdir($dir));
sort($files);
closedir($handle);
}
And then list them using foreach:
$blacklist = array('.','..','somedir','somefile.php');
foreach ($files as $file) {
if (!in_array($file, $blacklist)) {
echo "<li>$file</a>\n <ul class=\"sub\">";
}
}
Using scandir()
This is a lot easier with scandir(). It performs the sorting for you by default. The same functionality can be achieved with the following code:
$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');
// get everything except hidden files
$files = preg_grep('/^([^.])/', scandir($path));
foreach ($files as $file) {
if (!in_array($file, $blacklist)) {
echo "<li>$file</a>\n <ul class=\"sub\">";
}
}
Using DirectoryIterator (preferred)
$path = "/path/to/file";
$blacklist = array('somedir','somefile.php');
foreach (new DirectoryIterator($path) as $fileInfo) {
if($fileInfo->isDot()) continue;
$file = $path.$fileInfo->getFilename();
echo "<li>$file</a>\n <ul class=\"sub\">";
}
This is the way I would do it
if(!($dp = opendir($def_dir))) die ("Cannot open Directory.");
while($file = readdir($dp))
{
if($file != '.')
{
$uts=filemtime($file).md5($file);
$fole_array[$uts] .= $file;
}
}
closedir($dp);
krsort($fole_array);
foreach ($fole_array as $key => $dir_name) {
#echo "Key: $key; Value: $dir_name<br />\n";
}
Note: Move this into the foreach loop so that the newstring variable gets renamed correctly.
// strips files extensions
$crap = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-");
$newstring = str_replace($crap, " ", $file );
$directory = scandir('Images');

Categories