Using php to rename all files in folder

27,391

Solution 1

Here is the simple solution:

PHP Code:

// your folder name, here I am using templates in root
$directory = 'templates/';
foreach (glob($directory."*.html") as $filename) {
    $file = realpath($filename);
    rename($file, str_replace(".html",".php",$file));
}

Above code will convert all .html file in .php

Solution 2

You're probably working in the wrong directory. Make sure to prefix $fileName and $newName with the directory.

In particular, opendir and readdir don't communicate any information on the present working directory to rename. readdir only returns the file's name, not its path. So you're passing just the file name to rename.

Something like below should work better:

$directory = '/public_html/testfolder/';
if ($handle = opendir($directory)) { 
    while (false !== ($fileName = readdir($handle))) {     
        $newName = str_replace(".php",".html",$fileName);
        rename($directory . $fileName, $directory . $newName);
    }
    closedir($handle);
}
Share:
27,391
Munner
Author by

Munner

Updated on July 03, 2020

Comments

  • Munner
    Munner almost 4 years

    new php programmer here. I have been trying to rename all the files in a folder by replacing the extension.

    The code I'm using is from the answer to a similar question on SO.

    if ($handle = opendir('/public_html/testfolder/')) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = str_replace(".php",".html",$fileName);
        rename($fileName, $newName);
    }
    closedir($handle);
    

    }

    I get no errors when running the code, but no changes are made to the filenames.

    Any insight on why this isn't working? My permission settings should allow it.

    Thanks in advance.

    EDIT: I get a blank page when checking the return value of rename(), now trying something with glob() which might be a better option than opendir...?

    EDIT 2: With the 2nd code snippet below, I can print the contents of $newfiles. So the array exists, but the str_replace + rename() snippet fails to change the filename.

    $files = glob('testfolder/*');
    
    
    foreach($files as $newfiles) 
        {
    
        //This code doesn't work:
    
                $change = str_replace('php','html',$newfiles);
        rename($newfiles,$change);
    
               // But printing $newfiles works fine
               print_r($newfiles);
    }