Home > Article > Backend Development > How to modify file name suffix in PHP_PHP tutorial
There is a need to change the file type of a specified type in the current directory. I originally wanted to use batch processing to do this, but I couldn't find a suitable one. I checked the information myself and used PHP to process it. I don't deal with files very often, so I'm not very familiar with directory traversal. I searched for information and modified it myself.
The main purpose of the code is to change file suffixes in batches. Since the types of images in Taobao data packets are different, you need to change them appropriately.
<?php //本文件和要改变的目录下的文件 放在同一文件夹下 define("STA",".gif"); //原来的文件格式 define("END",".jpeg2000"); //要改变的格式 $dir="./"; $arr=allfile($dir); foreach($arr as $t) { $t=str_replace(".//","",$t); if(substr_count($t,STA)>0) { $f2=str_replace(STA,"",$t); rename($t,$f2.END); } } //获取目录下所有文件的函数 function allfile($dir) { $files=array(); if(is_file($dir)) { return $dir; } $handle = opendir($dir); if($handle) { while(false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..') { $filename = $dir . "/" . $file; if(is_file($filename)) { $files[] = $filename; } else { $files = array_merge($files, allfile($filename)); } } } // end while closedir($handle); } return $files; } ?>