Search code examples
phpoopiteratorrenamefile-rename

PHP7 Rename all files in directory within iterator (windows 10) 64-bit XAMPP


I need to rename all the songs to integer (numbers) with the following php code, but it shows an error:

Warning: rename(abc.mp3,2.4): The system cannot find the file specified. (code: 2) in D:\xampp\htdocs\hta\file_renames.php on line 14  

command PATHINFO_EXTENSION is also not working here? i am using windows 10 with xampp (php7)

<?php $total = 0;
$dir = "songs/";
foreach (new DirectoryIterator($dir) as $fileInfo) {
if(!$fileInfo->isDot()){
    $total +=1;
    $file = $fileInfo->getFilename();
    rename($file,$total.'.'.PATHINFO_EXTENSION);
}
}
echo('Total files: '.$total);
?>

how to rename my all .mp3 files to a number.mp3 file? within loop?


Solution

  • You need to supply the complete path (can be relative) to rename. Regarding the PATHINFO_EXTENSION, you are simply misusing it. Here is the fixed code:

    <?php
    $total = 0;
    $dir = "songs/";
    foreach (new DirectoryIterator($dir) as $fileInfo) {
        if(!$fileInfo->isDot()){
            $total +=1;
            $file = $dir.$fileInfo->getFilename();
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            $newFile = $dir.$total.'.'.$ext;
            rename($file, $newFile);
        }
    }
    echo('Total files: '.$total);
    ?>