Lodder
Lodder

Reputation: 19733

PHP - Delete file after upload

I've developed a small tool that allows a users upload a HTML file. Once uploaded, I run an Ajax request which gets the content of that HTML file and outputs it to a textarea.

PHP:

if (move_uploaded_file($src, $dest . $uploadfile)) 
{       
    echo $uploadfile;   
} 
else 
{
    echo "Error Uploading file";
}

Ajax:

$.get( "uploads/" + response, function(data) {
    $('#output').text(data);                                    
}); 

Everything is working so far.

Now what I want to do is delete that file once the content has been outputted to the textarea. I'm aware I could create a cron job to execute a script every X amount of minutes, however I would rather do it there and then.

I tried using the following, but naturally this deletes the file before the Ajax request is executed.

if (move_uploaded_file($src, $dest . $uploadfile)) 
{       
    echo $uploadfile;   

    if($delete) {  // $delete is a boolean argument for the function        
        unlink($dest . $uploadfile);
    }
} 

So how would I go about deleting the file once the content has been retrieved? Would I create another Ajax request to execute a delete function once the first request is complete? Or is there a way I can do this all at once?

Upvotes: 1

Views: 5646

Answers (1)

Steve
Steve

Reputation: 20469

Make your ajax request to a php file, that echos the content then deletes the file:

//ajax
$.get( "/get-file.php?file=uploads/" + response, function(data) {
    $('#output').text(data);                                    
});

.

//get-file.php
$file=$_GET['file'];
echo file_get_contents($file);
unlink($file);

Note that there are some security issues related to reading a user-submitted filename (they could pass in the filepath of a secure file, e.g. "passwords.php").

Better would be to store and retrieve the value from SESSION:

if (move_uploaded_file($src, $dest . $uploadfile)) 
{       
    $_SESSION['uploadedfile']=$dest . $uploadfile;
    echo 'success';//the return is no longer used   
} 
else 
{
    echo "Error Uploading file";
}

//ajax
$.get( "/get-file.php, function(data) {
    $('#output').text(data);                                    
});

.

//get-file.php
$file=$_SESSION['uploadedfile'];
echo file_get_contents($file);
unlink($file);

Upvotes: 3

Related Questions