简体   繁体   中英

Unable to rename all the files in a folder

I've been trying to change the file extension of all the picture files in a folder using the following snippet:

$dh = opendir('JS2C'); 
$files = array(); 
while (($file = readdir($dh)) !== false) { 
    if($file !== '.' && $file !== '..') {
        $file = pathinfo($file);
        rename($file, $new . '.jpg');
    }
}

I get the following warning messages:

SCREAM: Error suppression ignored for
Warning: rename(ANAZODO.gif,ANAZODO.jpg): 
The system cannot find the file specified. (code: 2) in C:\wamp2\www\ckcportal\batch2.php on ...

The folder that contains the files is in the same folder with the PHP script.

You have to supply the full path, from the error you are receiving, it looks like you are just giving the file name.

rename('/path/to/old/file', '/path/to/new/file');

And why are you using $file = pathinfo($file); ? pathinfo creates an assoc. array from information of $file which should be giving you the full path. If you take this out, it should work.

Unless you need to following:

$info = pathinfo($file);
$path = $info['dirname']

$new_file = $path . '/' . 'newfile.ext';

rename($file, $new_file);

you are missing directory for rename

$d = 'JS2C/'
$dh = opendir($d); 
while (($file = readdir($dh)) !== false) { 
    if($file !== '.' && $file !== '..') {
        //$file_no_ext = substr($file, 0,strrpos($file,'.'));// before php 5.2 

        $path_parts = pathinfo($file); // php 5.2
        $file_no_ext =  $path_parts['filename'];  // php 5.2

       rename($d.$file, $d.$file_no_ext . '.jpg');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM