dougou5852 2013-03-04 17:14
浏览 87

如何使用PHP顺序重命名文件夹中的文件?

I have files in a folder called 'thumbs'. They have names based on how they were named / renamed by their original authors. I would like to rename them to be two digit sequentially and I managed to find this PHP code:

function sequentialImages($path, $sort=false) {
 $i = 1;
 $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);

 if ( $sort !== false ) {
  usort($files, $sort);
 }

 $count = count($files);
 foreach ( $files as $file ) {
  $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);  
  }
  $i++;
 }
}

The php to execute this code is called 'rename.php' and it is found in a folder called 'admin'.

Therefore they are as follows

  1. 'admin' folder (contains rename.php')
  2. 'thumbs' folder (contains images with random names)

Both folders are on the same level.

How can I execute 'rename.php' if both are in different folders.

I tried to include $path = '../thumbs'; but it did not function.

Why isn't not working please?

  • 写回答

3条回答 默认 最新

  • dongshixingga7900 2013-03-04 17:24
    关注

    At the top of your function add:

    if( !is_dir($path) ) {
      die("error: $path is not a valid directory.");
      // or whatever error handling method you prefer
    }
    

    If, for some reason, parent paths are disabled on your server, or if there is some other issue with the path, you will be notified here.

    If that works fine, then step through your code and make sure that everything is as you expect it to be. eg: $files has the contents you expect, $newname is formatted properly, rename() is not returning false which indicates an error likely due to permissions, etc...

    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计