How to Force a Image File to Download Automatically in PHP

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

Welcome back folks today in this post we will be making a small app in which we will be forcing the browser to download the image file to download automatically when clicked by the user. Below a video is given of the demo application in which the user will hit the download button upon hitting the button automatically that image file will be forced to download in the browser.




Default Behaviour of Downloading Files in PHP


The default behaviour of downloading files in PHP is different. Let’s suppose you are downloading zip and exe files. Those files will be downloaded instantly but pdf and image files will be not. So in order to force the browser to download the image files we will be using a method in PHP called as readfile() function in PHP . So Just make a new file index.php and copy paste the below code into it.


In these lines of code we are using the image file as a query variable. The full path of the image file. For encoding image file in the url we are using a built in function in php called as urlencode() function. This function will sanitize the url string against any kind of special characters in the url. Now as you can see if user hit the download button then the control will be taken to download.php that file we will create in the next step. That file will handle the download part of the file. It will make sure that it forces the browser to download the file instantly when user clicks it.


In these lines of code we are just using the built in function readfile() to download the image instantly when the user clicks it. In this way you can force download of any file such as doc, pdf etc.

Leave a Reply