PHP batch modify file name/file suffix (extension)

Source: Internet
Author: User
Tags parent directory

Several key functions.

Is_dir ($ dirname) // determines whether a file name is a directory.
Opendir ($ dirname) // open a folder
Readdir ($ dir_stream) // the function returns the entries in the directory handle opened by opendir ().
Pathinfo ($ path) // the function returns the file path information in the form of an array.
For example, p10000036 in the current folder


For example, the following is an array of p10000036.jpg file paths under the folder:

Array
(
[Dirname] =>.
[Basename] => p1011236.jpg
[Extension] => jpg
[Filename] => p1038536
)
Rename (oldname, newname, context) // rename a file or directory. If the call succeeds, the function returns true. If it fails, false is returned.

The code is as follows: Copy code

 

<? Php
Function fileRename ($ dir, $ srcExtension, $ desExtension ){
If (! Is_dir ($ dir )){
Echo "{$ dir} is not a valid directory! N ";
Exit ();
  }
$ Handler = opendir ($ dir );
// List all objects in the $ dir Directory
While ($ fileName = readdir ($ handler ))! = False ){
If ($ fileName! = '.' & $ FileName! = '..'){
// '.' And '..' point to the current directory and the parent directory respectively.
$ CurDir = $ dir. '/'. $ fileName;
If (is_dir ($ curDir )){
// If the directory is used, recursive operation is performed.
FileRename ($ curDir, $ srcExtension, $ desExtension );
    }
Else {
// Obtain the file path information
$ Path = pathinfo ($ curDir );
// Print_r ($ path );
If ($ path ['extension'] ==$ srcExtension ){
$ Newname = $ path ['dirname']. '/'
. $ Path ['filename']. ".". $ desExtension;
Rename ($ curDir, $ newname );
Echo $ curDir. '-->'. $ newname. "n ";
      }
     }
   }
  }
 }
FileRename (".", "JPG", "jpg ");
?>


The usage method is very simple. We can keep the image in the same directory as the php file and then run php.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.