php - 如何从外部服务器上的文件推送 header 进行下载?

标签 php file download header

以下脚本是我通常用来将 header 推送到浏览器的脚本,以便出现供用户下载文件的对话框。

但是,在这种情况下,文件驻留在不同的服务器上。我认为这应该没有什么区别,但当我使用外部 MP3 文件的 URL 执行此脚本时,它会给出“错误:找不到文件”。但是,此文件存在,我可以使用传递给此脚本的相同 URL 来访问它。

有什么想法吗?我将不胜感激任何帮助。

<?php session_start();

//below variable contains full path to external site where file resides
$filename = $_SESSION['$serverURL'].'audio/'.$_SESSION['fileName'].'.mp3';
//below variable contains a chosen filename of the file to be downloaded
$properFilename = $_GET['properFilename'].'.mp3';

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

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  //echo "download file NOT SPECIFIED";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  //echo "ERROR: File not found";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($properFilename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();   

?>

最佳答案

单引号字符串不会被解析为变量,因此 $_SESSION['$serverURL'] 可能不会按您的预期工作。我怀疑您的意思是 $_SESSION[$serverURL]$_SESSION['serverURL']

同时调用 filesize() 然后调用 readfile() 可能会导致您的脚本发出两个 HTTP 请求以从其他服务器获取文件(除非该文件被缓存)不知何故)。您可以使用 cURL 在一个 HTTP 请求中完成此操作,这可能是更好的选择。这是一个简短的示例,您应该能够调整它来完成您想要的操作。您可能还需要考虑转发其他 header ,例如来自其他服务器的 Content-Type header (如果可靠),而不是自己重新生成它们。

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://example.com');

//set callbacks to receive headers and content
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'on_receive_header');
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'on_receive_content');

//send your other custom headers somewhere like here

if (false === curl_exec($ch)) {
    //handle error better than this.
    die(curl_error($ch));   
}

function on_receive_header($ch, $string) {
    //You could here forward the other headers received from your other server if you wanted

    //for now we only want Content-Length
    if (stripos($string, 'Content-Length') !== false) {
        header($string);   
    }

    //curl requires you to return the amount of data received
    $length = strlen($string);
    return $length;
}

function on_receive_content($ch, $string) {
    echo $string;

    //again return amount written
    $length = strlen($string);
    return $length;
}

关于php - 如何从外部服务器上的文件推送 header 进行下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/964973/

相关文章:

php - 如何在MySQL查询中获取新闻的计数作为别名列?

php:根据一年中的星期几和星期几计算日期

MATLAB - 'webread' 由于内容类型检查而变慢?

c#-4.0 - 向本地播放器提供 mp3,不显示 mp3 的位置

php - 模型文件 codeigniter 中的多个查询

java - 如何在 Java Eclipse 中读取文本文件?

java - 了解 ZipSecureFile.setMinInflateRatio(双比率)

android - 如何从 Android 的 Gallery 应用程序中隐藏一些图像(由我的应用程序保存在 sdcard 上)?

java - 如何使用 Jersey 下载 PDF 文件?

php - 使用 PHP 获取 &lt;script type ="application/ld+json"> 的内容