PHP visitFile of traverses the specified folder function

  • 2020-03-31 21:06:07
  • OfStack

Note :visitFile() has been slightly modified
 
<? 
//View the files in the specified folder
$fileList = array(); 
function visitFile($path) 
{ 
global $fileList; 
$path = str_replace("\", "/", $path); 
$fdir = dir($path); 
while (($file = $fdir->read()) !== false) 
{ 
if($file == '.' || $file == '..'){ continue; } 
$pathSub = preg_replace("*/{2,}*", "/", $path."/".$file); //Replace multiple backslashes
$fileList[] = is_dir($pathSub) ? $pathSub."/" : $pathSub; 
if(is_dir($pathSub)){ visitFile($pathSub); } 
} 
$fdir->close(); 
return $fileList; 
} 
?> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<form method="get"> 
<? 
$path = str_replace("\", "/", $path); 
$path = preg_replace("*/{2,}*", "/", $path); 
?> 
 The path :<input type="text" name="path" id="path" value="<?=$path;?>"/><br> 
<li> Disk root  /</li> 
<li> The local network  ./phpMyAdmin</li> 
<li> Local disk  file://C: or C: </ li>
<br> 
<input name="action" type="submit" id="action" value="view" /> 
<input name="action" type="submit" id="action" value="delete" onclick="if(!confirm(' Whether or not to delete  '+path.value+'  All subfolders and subfiles ?')) return false;" /> 
</form> 
<? 
if(!empty($path)){ 
$path = preg_replace("*/{2,}*", "/", $path); 
$files = visitFile($path); 
switch(strtolower($_GET["action"])) 
{ 
case "view": 
foreach($files as $key => $value) 
{ 
printf("No.%4d·%s<br>rn", $key+1, $value); 
} 
break; 
case "delete": 
$faileFiles = array(); 
foreach(array_reverse($files) as $value) 
{ 
if(!unlink($value)) 
{ 
array_push($faileFiles, $value); 
} 
} 
if(!unlink($path)) { array_push($faileFiles, $path); } 
if(count($faileFiles) > 0) 
{ 
printf("<br><br> Delete failed file (%d):<p>rn", count($faileFiles)); 
foreach( $faileFiles as $key => $value) 
{ 
printf("No.%4d·%s<br>rn", $key+1, $value); 
} 
} 
break; 
} 
} 
?> 

Related articles: