Monday 3 September 2018

Force file download code works on localhost but does not work on real server in PHP

I'm php programmer of beginner. I have write code to download file of any type.

When I click on download link it goes to download.php file. I work on local server but not working on server.
My code is:
header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');    //application/force-download
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit();

Is my code wrong or does server need some settings?

by using code written by me. this problem is solved. if anybody have same issue. please try this code. it works for me very good.
$file_name ='../img/files'.DS.$_GET['file'];
if(is_file($file_name)) {
        if(ini_get('zlib.output_compression')) {
                ini_set('zlib.output_compression', 'ON');
        }
        switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
                case 'pdf':  $mime = 'application/pdf'; break; // pdf files
                case 'zip':  $mime = 'application/zip'; break; // zip files
                case 'jpeg': $mime = 'image/jpeg'; break;// images jpeg
                case 'jpg':  $mime = 'image/jpg'; break;
                case 'mp3':  $mime = 'audio/mpeg'; break; // audio mp3 formats
                case 'doc':  $mime = 'application/msword'; break; // ms word
                case 'avi':  $mime = 'video/x-msvideo'; break;  // video avi format
                case 'txt':  $mime = 'text/plain'; break; // text files
                case 'xls':  $mime = 'application/vnd.ms-excel'; break; // ms excel
                default: $mime = 'application/force-download';
        }
    header('Content-Type:application/force-download');
        header('Pragma: public');       // required
        header('Expires: 0');           // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
        header('Content-Transfer-Encoding: binary');
        //header('Content-Length: '.filesize($file_name));      // provide file size
        header('Connection: close');
        readfile($file_name);
        exit();
}

0 comments:

Post a Comment