How to force downloading a file using PHP.

Here we are providing a simple code of explaining how to make a user to download file forcefully.

Normally, you don't necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file. 

<a href="demo.jpg">Download</a>

Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.

download.php
<?PHP
function force_download($file)  
{
       if ((isset($file))&&(file_exists($file))) {  
            header("Content-length: ".filesize($file));  
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $file . '"'); 
            readfile("$file");
       } else {  
            echo "No file selected";  
       }
}

index.php
<?php
include('download.php');
$file = 'demo.jpg'; 
force_download($file);
?>


HTTP header fields

The Content-Length entity-header field indicates the size of the entity-body,
in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
method, the size of the entity-body that would have been sent had the request
been a GET. 

The text/html content type is an Internet Media Type as well as a MIME content type. Using HTML in MIME messages allows the full richness of Web pages to be available in e-mail. text/plain[RFC1521] The text/plain content type is the generic subtype for plain text.

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.


List of HTTP header fields
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

Similarly, you can force download other files formats like word doc, pdf files, etc.

Labels

php (35) javascript (31) phpjavascript (30) jquery (23) html (20) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Popular Posts