1

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!

1
  • RTFM, then: arrays and foreach Commented Mar 12, 2014 at 14:51

2 Answers 2

5

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 />';
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

is there any other way rather than foreach?? like we pass an array of paths and that all files will be deleted at a time
0

also, i think its better if you use file_exists()

if (file_exists($file1)) 
{
unlink ( $_SERVER[DOCUMENT_ROOT]."/".$file1 );
clearstatcache();
}

3 Comments

why? what happens if you unlink a file that does no exist?
@njzk2 it's just a precaution, if file is locked or otherwise not accessible at that time. file_eixsts() will throw an error - that's why i remove the @ at the start of the unlink also.
If file does not exist, it will silently return false, no need file_exists.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.