MtDemonics
MtDemonics

Reputation: 235

How to sequentially rename files in a folder using 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?

Upvotes: 1

Views: 560

Answers (3)

Louis Ricci
Louis Ricci

Reputation: 21086

$path = realpath(__DIR__ . '/..') . '/thumbs';

realpath() function: http://php.net/manual/en/function.realpath.php

DIR (and other magic constants): http://php.net/manual/en/language.constants.predefined.php

Upvotes: 0

Lavesson
Lavesson

Reputation: 46

I think I would start by checking if you're actually getting any errors reported at all. Since you're saying that you only get a blank page without any errors it could be as simple as enabling error reporting to see what actually goes wrong.

If, for instance, PHP doesn't have write access to the thumbs-folder you'll probably get a bunch of warnings when you try to rename the files. Check your php.ini and make sure that display_errors = On, run the script again and check if you get any helpful error messages.

Not sure if that helps you (or if display_errors is already set to on), but that would be the first step that I would try, which hopefully gives you a little more details about what's going wrong.

Upvotes: 1

Sammitch
Sammitch

Reputation: 32232

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...

Upvotes: 0

Related Questions