简体   繁体   中英

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?

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);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM