php resource centre

  • about
  • articles
  • tutorials
  • resources
  • certification
Home

Primary links

  • About
  • Articles
  • Tutorials
  • Resources
  • Certification

Force download files using PHP

admin — Wed, 07/03/2007 - 3:06pm

At times we might want to give files for users to download. Also you wouldn't want to have the file storage location in a public access folder. To achieve these, you can store the file in an internal folder which is not accesible to public via a URL, and force the file to be downloaded using php header.

 The following code illustrates this method. Save this as download.php and pass the file as a parameter to it. 

<?
        //Get the file name passed to the script
        $filename = $_GET['dl'];
        
        //Absolute path the the file to be downloaded
        $dlfile = "/var/www/files/".$filename;
        
        // open the file and read it to a string
        $file_from   = fopen($dlfile,"r");
    $i           = 0;
    $data        = "";
    while ( $row = fread($file_from,filesize($dlfile)) ) {
      ++$i;
      $data .= $row;
    }
    fclose($file_from);
    
    /*
    By using the header option we tell the browser that the file format is not
    something which it can open. In the second line we are specifying the default file name.
    */
    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename="".$filename."";");
    header("Content-Transfer-Encoding: binary");
    header("Cache-Control: cache, must-revalidate");
    header("Pragma: public");
    header("Expires: 0");
    
    /* We are storing the data and sending it to the client machine through the file download.*/
    echo $data;
    exit();
?>

  • Tutorials
  • Login to post comments

User login

  • Request new password

Follow Us

Who's online

There are currently 0 users and 1 guest online.

Who's new

  • Nisha
  • linnaeus
  • Yameen
  • TalleyReedy
  • admin

Follow vipin7873 on Twitter

  • about
  • articles
  • tutorials
  • resources
  • certification

copyright © 2010 Vipin Chandran