Search code examples
phpajaxresponseunlink

how to unlink file in php after ajax callback is received


For creating a .zip file, i send the response back to ajax.

My php

// Multiple download (checkboxes)
if(isset($_POST["checkboxes_down"])) { 

    // create a tmp folder for the zip file
    $tmpfolder = $MainFolderName.'/tmpzip';
    if (!is_dir($tmpfolder)) {
         mkdir($tmpfolder, 0755, true);
    }

    $checkboxfiles = explode("," , $_POST["checkboxes_down"]); 
    $filename = "archive.zip";
    $filepath = $tmpfolder."/";

    foreach($checkboxfiles as $checkboxfile) {              
        Zip($checkboxfile, $tmpfolder."/archive.zip");
    }   

    // send the path to file back as response
    echo $filepath.$filename;

    unlink($tmpfolder.'/archive.zip'); // unlink archive.zip            
    rmdir($tmpfolder); // remove tmpdir
    exit;

}

my jquery ajax:

 $.ajax({  
            url:"",                                 
            method:"POST",  

            data:{ checkboxes_down:checkboxes_down },  
            success:function(response){                                 
               window.location = response; // redirec to .zip file for download
            }

I was hoping that the response and redirect was quicker then the unlink from the tmpfolder. But unfortunately, i can not use the unlink the way i created it in the php file.

So how can i unlink the tmpfolder after response is successful and redirected?Should i use something as a delay before unlinking?


Solution

  • The simplest option would be to scrap Ajax, use a regular form submission, and then output the zip file directly as the response instead of writing a file to disk.