Wednesday, February 16, 2022

Find file and remove from whole folder by php code

 Hello

Here I explain find the specific file and remove it from whole folder. 

For example: There is many .htaccess files in every folder. Or any file created by virus or any script. You want to remove it. So you have to open every folder and remove it. Instead of this you can remove it by this code.


<?php
function getDirContents($dir, &$results = array()) {
    $files = scandir($dir);
    foreach ($files as $key => $value) {
        $path = realpath($dir . DIRECTORY_SEPARATOR . $value);
        if (!is_dir($path)) {
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }
    return $results;
}
$i =1;
$files = getDirContents('FolderName');
foreach($files as $file){ // iterate files
  if (strpos($file, '.htaccess') !== false) {
    if (unlink($file)) {
  echo $i. "Delete file :".$file."<br>"; 
  $i++;
  }
}
}
?>


FolderName  means your website folder name

No comments:

Post a Comment