user3877230 user3877230 - 2 months ago 9
PHP Question

Renaming files in PHP?

I want the script to go into the folder 'images', take every file, cut the first four characters and rename it.

PHP

<?php
$path = './images/';

if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;

rename($fileName, $newName);
}
}

closedir($handle);
}
?>


This is how the files in the images folder are named:

0,78test-1.jpg
0,32test-2.jpg
0,43test-3.jpg
0,99test-4.jpg


and this is what i want them to look like:

test-1.jpg
test-2.jpg
test-3.jpg
test-4.jpg


The problem is the script cuts out the first 8, 12 or 16 characters, not four as i want it! So when i execute it my files look like this:

-1.jpg
-2.jpg
-3.jpg
-4.jpg


UPDATE

I also tracked the packages to make sure i am not executing the script multiple times. The script is only executed once!

Answer

A slightly different approach though essentially the same with the substr part this worked fine for tests on local system.

$dir='c:/temp2/tmpimgs/';
$files=glob( $dir . '*.*' );
$files=preg_grep( '@(\.jpg$|\.jpeg$|\.png$)@i', $files );


foreach( $files as $filename ){
    try{

        $path=pathinfo( $filename, PATHINFO_DIRNAME );
        $name=pathinfo( $filename, PATHINFO_BASENAME );
        $newname=$path . DIRECTORY_SEPARATOR . substr( $name, 4, strlen( $name ) );

        if( strlen( $filename ) > 4 ) rename( $filename, $newname );

    } catch( Exception $e ){
        echo $e->getTraceAsString();
    }
}
Comments