Rename all files in a directory with numbers - php

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.

Related

php rename error: The system cannot find the file specified. (code: 2)

<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($oldname, $newName);
$i++;
}
}
?>
when i run above script, i am getting following error:
The system cannot find the file specified. (code: 2)
$dir is not a string. You can't concatenate $file with it. You will need to put the directory in a separate variable, and not forget to put a / in between directory and filename.
Adding $dir in the rename() works for me
<?php
$dir = opendir('C:\Users\Prometheus\Desktop\milkmaid');
$i = 1;
// loop through all the files in the directory
while (false !== ($file = readdir($dir)))
{
if ($file != "." && $file != "..") {
$newName = $i.'.mp4';
$oldname = $file;
rename($dir.$oldname, $dir.$newName);
$i++;
}
}
?>
Use it like this :-
$directory = '/public_html/testfolder/';
$i=1;
if ($handle = opendir($directory)) {
while (false !== ($fileName = readdir($handle))) {
$newName = $i.'.mp4';
rename($directory . $fileName, $directory . $newName);
$i++:
}
closedir($handle);
}
This worked for me
<?php
$counter = 1;
$dir = 'D:\files'; //path of folder
if ($handle = opendir($dir))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName != '.' && $fileName != '..')
{
$newName = $counter . " - " . $fileName;
rename($dir."/".$fileName, $dir."/".$newName);
$counter++;
}
}
closedir($handle);
}
?>

PHP Sort directories by contents

I am trying to sort a list of directories according to the contents of a text file within each directory.
So far, I am displaying the list of directories:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
array_push($files, $file);
}
}
closedir($handle);
}
//Display tasks
sort($files);
foreach ($files as $file)
{
echo "$file";
}
Each directory has a text file within it called due.txt, I would like to sort the list of directories according to the contents of this file due.txt.
So far, I have tried:
$user = $_GET['user'];
$task_list = $_GET['list'];
if ($handle = opendir("../users/$user/tasks/$task_list/"))
{
$files = array();
$tasksSort = array();
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != ".." && $file != ".htaccess")
{
$taskSort = file_get_contents("../users/$user/tasks/$task_list/$file/due.txt");
array_push($files, $file);
array_push($tasksSort, $taskSort);
}
closedir($handle);
}
//Sort tasks and display
sort($tasksSort);
foreach ($files as $file)
{
echo "$file";
}
}
But the $tasksSort array doesn't seem to have any content to sort...?
sort($tasksSort);
foreach ($tasksSort as $file)
{
echo "$file";
}

Bulk Rename Files in a Folder - 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);
}

PHP list directories and remove .. and

I created a script that list the directories in the current directory
<?php
$dir = getcwd();
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file)){
echo "$file<br />";
}
}
?>
but the problem is, I am seeing this ".." and "." right above the directory listings, when someone clicks it, they get redirected one level up the directories.. can someone tell me how to remove those ".." and "." ?
If you use opendir/readdir/closedir functions, you have to check manually:
<?php
if ($handle = opendir($dir)) {
while ($file = readdir($handle)) {
if ($file === '.' || $file === '..' || !is_dir($file)) continue;
echo "$file<br />";
}
}
?>
If you want to use DirectoryIterator, there is isDot() method:
<?php
$iterator = new DirectoryIterator($dir);
foreach ($iterator as $fileInfo) {
if ($fileInfo->isDot() || !$fileInfo->isDir()) continue;
$file = $fileinfo->getFilename();
echo "$file<br />";
}
?>
Note: I think that continue can simplify this kind of loops by reducing indentation level.
Or use glob:
foreach(glob('/path/*.*') as $file) {
printf('%s<br/>', $file, $file);
}
If your files don't follow the filename dot extension pattern, use
array_filter(glob('/path/*'), 'is_file')
to get an array of (non-hidden) filenames only.
Skips all hidden and "dot directories":
while($file = readdir($handle)){
if (substr($file, 0, 1) == '.') {
continue;
}
Skips dot directories:
while($file = readdir($handle)){
if ($file == '.' || $file == '..') {
continue;
}
<?php
if($handle = opendir($dir)){
while($file = readdir($handle)){
if(is_dir($file) && $file !== '.' && $file !== '..'){
echo "$file<br />";
}
}
}
?>

Evaluating PHP Code

I am very much a beginner when it comes to using PHP. I was given this code, to try and output the contents of a files on a folder, onto a server, but my issue is I do not know how to read and alter this code to fit my specific file path. Can someone help me out with this, and lets just use the name folder as an arbitrary pathname.
<?php
if ($handle = opendir('.')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$dir_path = '.'; // '.' = current directory.
// '..' = parent directory.
// '/foo' = directory foo in the root file system
// 'folder' = a dir called 'folder' inside the current dir
// 'a/b' = folder 'b' inside 'a' inside the current dir
// '../a' = folder 'a' inside the parent directory
if ($handle = opendir($dir_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
<?php
$path = '.';
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
?>
Detailed explanation and examples: http://www.php.net/function.opendir

Categories