Search code examples
phpfilepathfilepathunlink

PHP unlink (delele ) multiple files on server


Sometimes, I have to delete multiple files in different folders on the server. It's a tedious job to to this one by one via FTP. I wrote a little script that does the job. I can import the list of files in Excel and copy and paste them in the script. However, my approach is not elegant:

$file1 = "some-file.php";
$file12 = "some-file2.php";

...

if (!empty($file1)) {
if ( @unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 ) )
{
  echo 'The file <strong><span style="color:green;">' . $file1 . '</span></strong> was deleted!<br />';
}
else
{
  echo 'Couldn't delete the file <strong><span style="color:red;">' . $file1 . '</span></strong>!<br />';
}}
if (!empty($file2)) { ...

I would rather like to do this with a foreach and an array, but don't know how. Any help would be appreciated!


Solution

  • Just put your files into an array and loop it.

    $files = array('some-file.php', 'some-file2.php');
    
    foreach ($files as $file) {
      if ( @unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file ) ) {
        echo 'The file <strong><span style="color:green;">' . $file . '</span></strong> was deleted!<br />';
      } else {
        echo 'Couldn\'t delete the file <strong><span style="color:red;">' . $file . '</span></strong>!<br />';
      }
    }