Home > Software engineering >  Deleting all files of a folder including script itself in php
Deleting all files of a folder including script itself in php

Time:10-24

Suppose I have a folder name 'tempF' now i want to write a script in php inside the folder so that whenever the file is hit it will delete all the files inside 'tempF' including the script itself. What is the best possible way to do it in php. I have tried recursive unlink but it is not deleting the script itself.

Thanks in advance.

CodePudding user response:

I think there is an answer here 'How to delete all files inside a specific folder using php'

array_map('unlink', glob("some/dir/*.txt"));

CodePudding user response:

I assume you are talking about a PHP script run thru a web-browser http visit.

Assuming that the folder itself and the files (including the PHP script) are write-permitted, then you can delete the files (including the PHP script).

Just use glob to get all the files and then use unlink to delete.

<?php


$files = glob('./*'); // get all file names
foreach($files as $file){ // iterate files
  if(is_file($file)) {
 
echo $file;
echo "<br>";

    unlink($file); // delete file

  }
}

?>

So after running this file (ONCE), if you run again (thru a browser visit), it will return 404 (because it has been deleted) .

  • Related