簡體   English   中英

從外部URL下載文件,並直接將文件傳遞給用戶,而不將其保存在我的服務器上。

[英]download files from external url, and pass the file to user directly, without saving it on my server.

基本上我想從外部主機下載文件並將其直接傳遞給用戶而不必保存在服務器上,實際上,充當該文件的代理,以便始終從我的服務器發出請求而不是用戶。 我應該模擬這個請求:

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和所有必需的標題,但我無法開始下載,我嘗試在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;

它會像魅力一樣工作!

您可以簡單地將要下載的文件的URI放入超鏈接的值:

<a href="URI" target="_blank">Click to download</a>

如果您不希望它們單擊任何內容,並立即下載文件,則可以使用php header()函數。 請參見此處的示例1: http//uk.php.net/manual/en/function.header.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM