Search code examples
phparraysphpmailerunlink

Unlinking files in PHP array (PHPMailer)


Just a simple question -hello btw, it keeps deleting me my greeting.

This is how I go through an array and upload files

$numFiles = count(array_filter($_FILES['priloha']['name']));

for ($i = 0; $i < $numFiles; ++$i) {
  $target_path = './' . basename($_FILES['priloha']['name'][$i]);
  if(move_uploaded_file($_FILES['priloha']['tmp_name'][$i], $target_path)) 
  {
  echo "Soubor ".basename($_FILES['priloha']['name'][$i])." byl úspěšně nahrán.<br />";
  }
$mail->AddAttachment($target_path);
}

Now after sending, I need to go through the array again and delete all the files like I did with a single file (not an array)

if  ($mail->AddAttachment($target_path); !="")
  {
  unlink("$target_path");
  }

How is the code gonna look like? I'm not really sure, I still don't know what can I delete from the first "for" cycle. Thanks for your help

Solved, thanks Ivo Pereira :)


Solution

  • Try this. You only delete the file if is it has been successfully sent.

    $numFiles = count(array_filter($_FILES['priloha']['name']));
    
    for ($i = 0; $i < $numFiles; ++$i) {
          $target_path = './' . basename($_FILES['priloha']['name'][$i]);
          if(move_uploaded_file($_FILES['priloha']['tmp_name'][$i], $target_path)) 
          {
          echo "Soubor ".basename($_FILES['priloha']['name'][$i])." byl úspěšně nahrán.<br />";
    
          }
    
    
        if  ($mail->AddAttachment($target_path) )
        {
          unlink("$target_path");
        }
    
    }