force download file using php



By default most of the file types (eg: txt, jpg, png, gif, html, pdf, etc.) displayed in browser instead of download. But we can force browser to download these files instead of showing them.This tutorial goes over how to force file download in php.

<?php
   //file path to download
    $file_name=$_GET['file'];
    $outputfilename = "<DOWNLOAD_FILE_NAME>";
    header('Content-Description: File Transfer');
    //set content type
    header('Content-Type: application/octet-stream');
    //file name to save it may be different from original filename
    header("Content-Disposition:  attachment; filename=\"" . basename($outputfilename) . "\";" );
    //sends file size header to browser
    header('Content-Length: ' . filesize($file_name));
    header('Content-Transfer-Encoding: binary');
    header('Cache-Control: public');
    header('Pragma: public');
    ob_clean();
    //outputs file content to download stream
    readfile($file_name);
    exit;
?>

0 comments :