用php下载文件

时间:2014-03-16 08:21:34

标签: php download

我有一个PHP脚本从远程服务器下载文件(该网站托管在bluehost上),但是当我点击下载链接(按钮)时,我不会真正得到以下内容在我的浏览器中打开:

  

ELRY gnu|����������������&/8AKT]gqz������������!-8COZfr~���������� -;HUcq~��������� +:IXgw��������'7HYj{�������+=Oat�������2FZn������� % : O d y � � � � � � ' = T j � � � � � �"9Qi������*C\u����� & @ Z t � � � � �.Id���� %A^z���� &Ca~����1Om����&Ed����#Cc����'Ij����4Vx���&Il����Ae����@e���� Ek���*Qw���;c���*R{���Gp���@j���>i��� A l � � �!!H!u!�!�!�"'"U"�"�"�# #8#f#�#�#�$$M$|$�$�% %8%h%�%�%�&'&W&�&�&�''I'z'�'�( (?(q(�(�))8)k)�)�**5*h*�*�++6+i+�+�,,9,n,�,�--A-v-�-�..L.�.�.�/$/Z/�/�/�050l0�0�11J1�1�1�2*2c2�2�3 3F33�3�4+4e4�4�55M5�5�5�676r6�6�7$7 7788P8899B999:6:T :: ;;ķ;;<' >`>>?!一个??

以下是我使用

的代码
function output_file($file_id=0)
{
 /*
 This function takes a path to a file to output ($file),  the filename that the browser will see ($name) and  the MIME type of the file ($mime_type, optional).
 */
 //get filepath, filename and mime type from db
 $mysql_file = "SELECT filename, file_format
    FROM order_files
    WHERE order_files.fileID ={$file_id}";

    $myresult_file = mysql_query($mysql_file);
    if($myresult_file){
        while($myrow_file = mysql_fetch_array($myresult_file)){
            $filename = $myrow_file['filename'];
            $mimeType =$myrow_file['file_format'] ;
        }


    }

$file = '/home6/xxxxx/public_html/wp-content/themes/twentythirteen/inc/orderfiles/'.$filename;
$name = $filename;
$mime_type=$mimeType;   

 //Check the file premission
 if(!is_readable($file)) die('File not found or inaccessible!');

 $size = filesize($file);
 $name = rawurldecode($name);

 /* Figure out the MIME type | Check in array */
 $known_mime_types=array(
    "pdf" => "application/pdf",
    "txt" => "text/plain",
    "html" => "text/html",
    "htm" => "text/html",
    "exe" => "application/octet-stream",
    "zip" => "application/zip",
    "doc" => "application/msword",
    "xls" => "application/vnd.ms-excel",
    "ppt" => "application/vnd.ms-powerpoint",
    "gif" => "image/gif",
    "png" => "image/png",
    "jpeg"=> "image/jpg",
    "jpg" =>  "image/jpg",
    "php" => "text/plain"
 );

 if($mime_type==''){
     $file_extension = strtolower(substr(strrchr($file,"."),1));
     if(array_key_exists($file_extension, $known_mime_types)){
        $mime_type=$known_mime_types[$file_extension];
     } else {
        $mime_type="application/force-download";
     };
 };

 //turn off output buffering to decrease cpu usage
 @ob_end_clean(); 

 // required for IE, otherwise Content-Disposition may be ignored
 if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

 header('Content-Type: ' . $mime_type);
 header('Content-Disposition: attachment; filename="'.$name.'"');
 header("Content-Transfer-Encoding: binary");
 header('Accept-Ranges: bytes');

 /* The three lines below basically make the 
    download non-cacheable */
 header("Cache-control: private");
 header('Pragma: private');
 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");

 // multipart-download and download resuming support
 if(isset($_SERVER['HTTP_RANGE']))
 {
    list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
    list($range) = explode(",",$range,2);
    list($range, $range_end) = explode("-", $range);
    $range=intval($range);
    if(!$range_end) {
        $range_end=$size-1;
    } else {
        $range_end=intval($range_end);
    }
    /*
    ------------------------------------------------------------------------------------------------------
    //This application is developed by www.webinfopedia.com
    //visit www.webinfopedia.com for PHP,Mysql,html5 and Designing tutorials for FREE!!!
    ------------------------------------------------------------------------------------------------------
    */
    $new_length = $range_end-$range+1;
    header("HTTP/1.1 206 Partial Content");
    header("Content-Length: $new_length");
    header("Content-Range: bytes $range-$range_end/$size");
 } else {
    $new_length=$size;
    header("Content-Length: ".$size);
 }

 /* Will output the file itself */
 $chunksize = 1*(1024*1024); //you may want to change this
 $bytes_send = 0;
 if ($file = fopen($file, 'r'))
 {
    if(isset($_SERVER['HTTP_RANGE']))
    fseek($file, $range);

    while(!feof($file) && 
        (!connection_aborted()) && 
        ($bytes_send<$new_length)
          )
    {
        $buffer = fread($file, $chunksize);
        print($buffer); //echo($buffer); // can also possible
        flush();
        $bytes_send += strlen($buffer);
    }
 fclose($file);
 } else
 //If no permissiion
 die('Error - can not open file.');
 //die
die();
}
//Set the time out
set_time_limit(0);

这是什么意思,我该如何调试它? 我是php的新手,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

确保您强制下载文件而不是在浏览器中显示

http://hiryu.byethost7.com/2013/06/force-file-download-in-php/

试试这个 添加这些标题

 header("Content-Type: " . $file_head['Content-Type']);
  header("Content-Transfer-Encoding: Binary");
  header("Accept-Ranges: bytes");
  header("Content-Disposition: attachment; filename=" . basename($url) . ";");
  header("Content-Description: File Transfer");
  header("Expires: 0");
  header("Pragma: public");
  header("Content-Length: " . $file_head['Content-Length']);
  header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  header("Connection: close");