Rahul Gupta
Rahul Gupta

Reputation: 75

Disable opening of popup when downloading a file

I am creating a wordpress page that allows users to downloads a zip file after 5 secs. In it, I am calling a second page and pass POST parameters ( zip id :: to fetch zip path). The page is called but always as a pop up. I am looking for a clean download options, where without opening tabs or new window, download begins. Bypasses popup - blockers also.

I have tried two methods

A) Method 1 ( Jquery Post)

$.post(
        "<?php echo get_permalink(get_page_by_title('Download Page')); ?>",
        {attachment_path: "<?php echo $attachment[0]->ID ; ?>"
    }

B) Method 2 (Submitting a form)

$( '<form action="" method="post" target="_parent" class="hide">
       <input type="hidden" name="attachment_path" value="<?php echo $attachment[0]->ID ; ?>" />
       <input type="submit" name="submit" value="submit" id="target-counter-button"/>
    </form>'
   ).submit();  

Edit

1) Looking for a POST method to implement the logic

2) Due to server restrictions, direct access to *.php files and *.zip files have been blocked

3) Parent Download Page should remain open in the process

Looking for a expert advice on this issue.

Thanks

Upvotes: 2

Views: 2944

Answers (1)

Isaac
Isaac

Reputation: 983

You can achieve this by doing a redirect to the path of php script how will output the wanted file with correct HTTP Headers.

Javascript Part :

Redirect after 5 second to the 'zipfetcher' script with the zip id

<script>
function download(id) {
    setTimeout(function () {
        document.location = "zipfetcher.php?fileid="+id; // The path of the file to download
    }, 5000); // Wait Time in milli seconds
}
</script>

<a href="#" onclick="download('123');return false;">Click to download in 5 sec!</a> // Call of the download function when clicked

PHP Part : (aka zipfetcher.php)

Find the zip path according to zipid then outpout it using readfile to the browser with the correct header

// Fetch the file path according to $_GET['fileid'] who's been sent by the download javascript function etc.
// ....

header('Content-Description: File Transfer');
header('Content-Type: application/zip, application/octet-stream'); // Puting the right content type in this case application/zip, application/octet-stream
header('Content-Disposition: attachment; filename='.basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;

Upvotes: 1

Related Questions