Looking to Build/Redesign a Website or Blog ?

To speak to Rakshit, call +91 968 704 2303

Force Download Image JPG/PNG/GIF Files using PHP Javascript or htaccess

Hi Friends,

I was working with premium image web site where client want a facility for their registered users to download the image files directly to their PC. If you have zip file and if you open it in tab, it will show you popup to save it. so you can download it and file will be saved to your PC.

For Image JPG/PNG/GIF files, case is not the same. If you try to open it in new tab, it will not show popup with save and cancel button. It will just open in new tab and shows image there. so question is how to Force Download Image JPG/PNG/GIF Files using PHP ? Here is a code to force download image files.

Code for Force Download Image JPG/PNG/GIF Files using PHP

function force_download_file($file) {				
 header( 'Expires: Mon, 1 Apr 1974 05:00:00 GMT' );
 header( 'Pragma: no-cache' );
 header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
 header( 'Content-Description: File Download' );
 header( 'Content-Type: application/octet-stream' );
 header( 'Content-Length: '.filesize( $file ) );
 header( 'Content-Disposition: attachment; filename="'.basename( $file ).'"' );
 header( 'Content-Transfer-Encoding: binary' );
 readfile( $file );  
 exit();
}

You can call this function when you click on Download Button and process. It will show you pop up.

Code for Force Download Image JPG/PNG/GIF Files using Javascript

<a href="javascript:;" onclick="document.execCommand('SaveAs',true,'rakshit.jpg');">Download Image</a>

Code for Force Download Image JPG/PNG/GIF Files using htaccess

If you want force download feature for all images in your site, you can use below code in htaccess. Now if anyone click on any link of image on your site, it will show force download popup.

<FilesMatch "\.(?i:jpg|gif|png)$">
Header set Content-Disposition attachment
</FilesMatch>
Share:

No Comments Yet.

Leave a Reply

Your email address will not be published.