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="">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.


  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('') ?>">Download</a>

# download.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

# terminate current script


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
Notify of
Inline Feedbacks
View all comments