Leave a comment

How To Use PHP to Force a File Download?

Force Dolnload

How To Use PHP to Force a File Download?

PHP to Force a File Download step by step is:

Step 1. Upload the file you want to make available for download to your web server. For example,

document.pdf

Step 2. Edit a new PHP file in your web editor—I recommend naming it the same name as your downloaded file, only with the extension .php. For example:

document.php

Step 3. Open the PHP block:

<?php

Step 4. On the next line, set the HTTP header:

header("Content-disposition: attachment; filename= document.pdf");

Step 5. Then set the MIME-type of the file:

header("Content-type: application/pdf");

Step 6. Point to the file you want to download:

readfile("document.pdf");

Step 7. Then close the PHP block and save the file:

?>

Step 8. Your PHP file should look like this:

<?php
 header("Content-disposition: attachment; filename=document.pdf");
 header("Content-type: application/pdf");
 readfile("document.pdf");
 ?>

Link to your PHP file as a download link. For example:

<a href="document.php">Download my document (PDF)</a>

You can download code here Forcedownload.zip

Leave a comment