php - 从外部 url 下载文件,并将文件直接传递给用户,而不将其保存在我的服务器上。

标签 php url download external

基本上我想从外部主机下载一个文件并将其直接传递给用户而不必保存在服务器上,实际上,充当这个文件的代理,这样请求总是从我的服务器而不是用户。 我应该模拟这个请求吗:

GET / servername / filename.ext HTTP/1.1 (any large file) 
Host: namehost 
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv: 27.0) Gecko/20100101 Firefox/27.0 
Accept: text / html, application / xhtml + xml, application / xml; q = 0.9, * / * q = 0.8 
Accept-Language: en-us, en; q = 0.8, en-US; q = 0.5, en; q = 0.3 
Accept-Encoding: gzip, deflate 
Referer: sitename / ... 
Cookie: .... 
Connection: keep-alive 

我已经有了必要的 cookie 和所有必要的 header ,但我无法开始下载,我尝试在 Curl 中使用不同的脚本,但下载没有开始。

谁能帮帮我

最佳答案

您想从远程服务器获取文件并将其提供给您的用户。下面是获取和服务代理示例代码。我希望您知道文件名、URL、文件扩展名和 MIME 类型

<?php
function get_size($url) {
    $my_ch = curl_init();
    curl_setopt($my_ch, CURLOPT_URL,$url);
    curl_setopt($my_ch, CURLOPT_HEADER, true);
    curl_setopt($my_ch, CURLOPT_NOBODY, true);
    curl_setopt($my_ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($my_ch, CURLOPT_TIMEOUT, 10);
    $r = curl_exec($my_ch);
    foreach(explode("\n", $r) as $header) {
        if(strpos($header, 'Content-Length:') === 0) {
            return trim(substr($header,16));
        }
    }
    return '';
}
// Set operation params
$mime = filter_var($_GET['mime']);
$ext = str_replace(array('/', 'x-'), '', strstr($mime, '/'));
$url = base64_decode(filter_var($_GET['url']));
$name = urldecode($_GET['title']). '.' .$ext;

// Fetch and serve
if ($url)
{
$size=get_size($url);
// Generate the server headers
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE)
{
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header('Expires: 0');
header('Content-Length: '.$size);
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Transfer-Encoding: binary");
header('Pragma: public');
}
else
{
header('Content-Type: "' . $mime . '"');
header('Content-Disposition: attachment; filename="' . $name . '"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Content-Length: '.$size);
header('Pragma: no-cache');
}

readfile($url);
exit;
}

// Not found
exit('File not found');
?>

使用方法:将其保存为download.php 并调用即可

$encoded_url =  base64_encode($file_to_download_url);
$download_url = 'http://www.example.com/download.php?mime='.$mime.'&title='.$title.'&url='.$encoded_url;

它会像魅力一样发挥作用!

关于php - 从外部 url 下载文件,并将文件直接传递给用户,而不将其保存在我的服务器上。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21707080/

相关文章:

php - WordPress 编辑器中的 "application/gas-events-abn"对象是什么?

php - 是否有必要取消设置 php 密码变量?

perl - 通过 Perl 的 URI 模块过滤 URL 可以获得什么?

url - 在 GWT 中,我想加载 www.domain.com 上的主页和 www.domain.com/xyz 上的动态页面 - 我只是无法使其工作

java - 下载图片会覆盖上一张图片

php - 我在哪里将 sql 语句存储在 blueimp/jQuery-File-Upload 的数据库中?

javascript - 如果内容不同,使用 ajax 更新页面

java - 格式错误的 Java Net URL

javascript - 将 Web 服务响应转换为 PDF 文件 - PHP、Javascript

java - 下载时 JAR 不兼容