rename all the image files in a specified directory

佐手、 提交于 2019-12-10 12:14:40

问题


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:

$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++;
      }
     }

}

回答1:


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');
// --------------------------------------- ^


来源:https://stackoverflow.com/questions/28705314/rename-all-the-image-files-in-a-specified-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!