Hi guys,
Could someone please help me with a rename function.
The code I have is:
<?php
$path = 'path/to/directory';
$dir_handle = opendir($path);
while ($file = readdir($dir_handle))
{
rename();
}
closedir($dir_handle);
?>
I have a bunch of images on my server which have been imported from another script, unfortunately during the import the script added a further extension to the file names. So I have files like: abc.jpg.jpg
I need to put a rename function into my script to change all the files in a directory with the .jpg.jpg extension to a .jpg extension (abc.jpg).
All the file names are different so i can’t do a clean sweep through the directory.
Any ideas?
Found this script, works very well.
<?php
function changeext($directory, $ext1, $ext2, $verbose = false) {
$num = 0;
if($curdir = opendir($directory)) {
while($file = readdir($curdir)) {
if($file != '.' && $file != '..') {
$srcfile = $directory . '/' . $file;
$string = "$file";
$str = strlen($ext1);
$str++;
$newfile = substr($string, 0, -$str);
$newfile = $newfile.'.'.$ext2;
$dstfile = $directory . '/' . $newfile;
if (eregi("\\.$ext1",$file)) { # Look at only files with a pre-defined extension
$fileHand = fopen($srcfile, 'r');
fclose($fileHand);
rename($srcfile, $dstfile );
}
if(is_dir($srcfile)) {
$num += changeext($srcfile, $ext1, $ext2, $verbose);
}
}
}
closedir($curdir);
}
return $num;
}
changeext('dir', 'jpg.jpg', 'jpg', 'false');
?>