If you want to download an image from the web, you may think that an anchor tag will do the job. Like this:
However, when you click on the download link, the browser will display the image instead of initiating the download. But why is that? Actually, your browser will open any type of file if it has the capability to read it, not just images. For instance, if the browser can read PDFs, all PDF files will be opened by the browser instead of downloading them. With that out of the way, how can we fix this? Well, you’ll have to force the download. With PHP, it’s really simple with just a few lines of code. Let’s see how to do that.
php.iniin order to let the readfile() method read remote URLs
- PHP 5.6 and above
- An image to download
You’ll need two files: index.php and download.php. index.php will initiate the download and download.php will force it.
# index.php # pass the image URL as an argument of a GET request <a href="download.php?url=<?= urlencode('https://cdn.pixabay.com/photo/2017/06/05/07/58/butterfly-2373175_960_720.png') ?>">Download</a> # download.php <?php # retrieve the image URL in the server side $image_url = $_GET['url']; # set some headers header('Content-Type: application/octet-stream'); header("Content-Transfer-Encoding: Binary"); header("Content-disposition: attachment; filename=\"" . basename($image_url) . "\""); # force download file readfile($image_url); # terminate current script exit();
There you have it. With just a few lines of code, you are now able to force the download of your images. This script will also work on any type of file. I hope you find this article useful and if so please share.