Feb 1, 2013

Download file using PHP

Downloading a file can be done in two ways:

  1. Direct download
  2. Indirect download
Direct Download:
Assumptions:
File location: c:/xampp/htdocs/project/docs/test.doc
URL: http://localhost/project/docs/test.doc

Code:  <a href='http://localhost/project/docs/test.doc'>click here</a>

Indirect Download:
(recommended)
Assumptions:
File location: c:/xampp/htdocs/project/docs/test.doc
PHP file for the download code:
location: c:/xampp/htdocs/project/download.php

<?php
  $file_name = $_GET['file'];
  $file_path = "docs/".$file_name;

 //setting the content type
  header('content-type: application/octet-stream');

  //downloads file as attachment
  header("content-disposition: attachment; filename='$file_name'");

  //actual file path
  readfile($file_path);

?>

Note: content-type application/octet-stream can be used for any type of file.

To use the above file for download. Create link like as below
<a href='http://localhost/project/download.php?file=test.doc'>click here</a>

For any queries or clarifications post a comment.

No comments:

Post a Comment

Want to tell something about this post. Please feel free to write...