PHP: Main
In this small tutorial, we are going to learn how to force a viewer to download a file when they click a link.
For example, if you want your viewers to be able to download the file image.jpg, you can use the code below, and the file image.jpg wont open in the browser.
To understand this tutorial you will need some basic knowledge of PHP and HTML.
So, on with the tutorial.
Make a new file called forceddownload.php and write the following script in it.
<?
// Tells the browser that where going to run a PHP script.
$file = $_GET['file'];
// Get a filename from the GET parameters.
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
// Sends the brower headers to tell it that it is sending that file back to it.
readfile($file);
// Reads the file from the server and send it to the browser.
exit;
?>
// Closes the PHP script.
Next, on the page you want to link the download from, we have the HTML that will link to the file.
<a href="forceddownload.php?file=image.jpg">D
ownload image.jpg</a>
Thats it.
You should now be able to click the link, and instead of the file opening, it will download.
Thanks to Cheeries for proof reading this tutorial =)
Brought to you by DannyIsOnFire.
www.dannyisonfire.com