Search code examples
phpfile-uploaddelete-file

PHP unset not working on files uploaded in same PHP script


I haven't had this issue for years, but this is making no sense to me... I upload a file, then I move it to AWS, then I want to delete the local file. unset() is not working, though.

First I just did it the way I do on all my similar situations:

$location =  $_FILES["file"]["tmp_name"];
$dest = $_SERVER['DOCUMENT_ROOT'].'/files/'.$filename;
move_uploaded_file($location,$dest);

//DO AWS UPLOAD STUFF//
//THEN,

if(file_exists($dest)){
   unset($dest);
}

However, this did not work. So I even tried to change file permissions (was 644, changed to 755) since I was going to delete immediately anyway. Just added

chmod($dest, 0755);

Right after moving the uploaded file. In both situations it does not delete the file. What am I missing?


Solution

  • unset just removes the in memory reference.

    If you're wanting to remove the physical file you want unlink()

    So your code will be

    $location =  $_FILES["file"]["tmp_name"];
    $dest = $_SERVER['DOCUMENT_ROOT'].'/files/'.$filename;
    move_uploaded_file($location,$dest);
    
    //DO AWS UPLOAD STUFF//
    //THEN,
    
    if(file_exists($dest)){
       unlink($dest);
    }
    

    Although that doesn't seem right, as you'll be moving the file and then deleting the file you've just moved.

    If you're wanting to confirm it was a move and not a copy, you'll need to change to:

    if(file_exists($dest) && file_exists($location)){
       unlink($location);
    }