Search code examples
phpfile-rename

rename all the image files in a specified directory


i am trying to create couple of lines of code which will rename all the jpg images in a specified directory.The parent directory was c:/xampp/htdocs/practice/haha/.But renamed images are saved in c:/xampp/htdocs/practice/

My code do rename the file ,but problem is it deletes all the image file form the specied directory leaving the directory empty.It stores the renamed file in root php directory.And the newly created files are not clickable image file.So there are two problem i want to solve.

  1. how can i keep the renamed files in the same directory where they were before any renaming occur.

2.How i can sustain them to be a clickable image file?

this is how they looked after renaming:

enter image description here

$dir='c:/xampp/htdocs/practice/haha/';
echo getcwd().'</br>';
$i=1;
if(is_dir($dir)){
echo dirname($dir);
     $file=opendir($dir);

     while(($data=readdir($file))!==false){
      $info=pathinfo($data,PATHINFO_EXTENSION);
      if($info=='jpg'){
         //echo pathinfo($data,PATHINFO_BASENAME).'</br>';
         echo basename(pathinfo($data,PATHINFO_BASENAME),'.jpg').'</br>';
         rename($dir.'/'.$data,'image'.$i.'jpg');
         $i++;
      }
     }

}

Solution

  • You missed a dot in the file name:

    rename($dir.'/'.$data,'image'.$i.'jpg');
    

    This is why they are not clickable. Use this instead:

    rename($dir . '/' . $data, 'image' . $i . '.jpg');
    // --------------------------------------- ^