Do not view PDF inside browser

Posted on

Question :

I have the following anchor:

   <a href="http://localhost/refazer/uploads/0503-14.pdf">Conteúdo</a>

By clicking this link the browser automatically recognizes that it is PDF and views it. As below:

Otherwise, I wanted the browser to start downloading when the browser clicked on the link.


Answer :

The common answer to this is that you should change the link instead of being a file using a server side page (PHP for example) and setting the http header to force the download.

However in HTML5 there is a new attribute download that does this, ie tells the browser that this link is for download. In the value of this new field you can enter the name of the file or not define to use what is in the link.

 <a href="http://localhost/refazer/uploads/0503-14.pdf" download>Conteúdo</a>

Example with a value in download that overrides the file name that was in href would be:

<a href="http://localhost/refazer/uploads/0503-14.pdf" download="ficheiro0503.pdf">Conteúdo</a>

Note: Browsers are gradually integrating the new HTML5 specifications. Today this does not work in all browsers, in a few months, or for the next year, this should be the common practice.


The way to do it in PHP is very simple


$file_url = $_GET['file'];
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename="" . basename($file_url) . """""")

Leave a Reply

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