Coding Triumph

Helpful code snippets & tutorials

How to force the image to download instead of open in the browser with PHP?

If you want to download an image from the web, you may think that an anchor tag will do the job. Like this:

<a href="https://cdn.pixabay.com/photo/2017/06/05/07/58/butterfly-2373175_960_720.png">Download</a>

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.

Prerequisite:

  1. Enable allow_fopen_url in php.ini in order to let the readfile() method read remote URLs
  2. PHP 5.6 and above
  3. An image to download

The script:

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();

Conclusion:

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.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments