Search code examples
phprenamebatch-rename

rename all the files in a folder


i have been trying to rename all the files (images) in a folder on my website but it does not work. the files are not renamed.

i have an input field for 'name' i want to use that name, add a uniqid and rename all the files. here's the code that i am using:

<?php
if(isset($_POST['submit2'])){
$name = $_POST['name'];
$directory = glob("../basic_images/*.*");
{
if ($file != "." && $file != "..") {

    $newName = uniqid().$name;

    rename($directory.$file, $directory.$newName);
}}}
?>

besides, do i really need to _Post the $name variable?

P.S. i want to rename all the files and then copy them to another folder.


Solution

  • You don't need to POST name

    glob is return you every files in folder with path // example /basic_images/test.jpg

    then you just do foreach to loop over files, and update its name.

    $path = "../basic_images/";
    $directory = glob($path,"*.*");
    foreach($directory as $file){
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $newName = uniqid().$ext;
        rename($file, $path.$newName);
    } 
    

    read more about glob : http://php.net/manual/en/function.glob.php