Force files to download in HTML and PHP

I am noticed that in some sites of you click on download button and file is type of image/music/video/pdf then in most of cases it play/open with in browser instead of downloading on client.
In this article i am writing certain snippet for how to force browser to download file rather then open in browser.

In PHP we can use hearer() for make browser to download file. First of all we need to set content-type of file to be download, then set content-disposion as attachment for download file, and set filename to be downloaded.

header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="downloaded.pdf"');

HTML5 allow us to download file through simple hyperlink without setting any headers. You need to use download attribute introduce in HTML5 of <a> tag. Download attribute specify name with which file is download on browser.

<a href="path_to/filename.pdf" download="download.pdf">Click here</a>

Leave a Reply

Your email address will not be published. Required fields are marked *