PHP changes the directory and subdirectory of all the file extension suffix code

  • 2020-03-31 21:11:55
  • OfStack

Not very often deal with the file, so the directory is not very familiar with traversal, looked for the data, modify their own.
Let's see if we need to improve it
The main purpose of the code is to change the file suffix in batches due to the different types of taobao data packet images so to change the appropriate.
 
<?php 
//This file is in the same folder as the files in the directory you want to change
define("STA",".gif");//Original file format
define("END",".jpg");//Format to change
$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); 
} 
} 
//Gets the function for all files in the directory
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; 
} 
?> 

String replacement is not too rigorous, in case the name of the GIF program there is an exception.
The PHP function pathinfo() is recommended, and the loop segment can be changed to
 
foreach($arr as $t) 
{ 
  $path_parts = pathinfo($t); 
  if($path_parts["extension"] == STA) 
  { 
    rename($t,$path_parts["dirname"]."/".basename($t,STA).END); 
  } 
} 

Related articles: