我正在通过php脚本下载文件,除了一个丑陋的事实外,一切都很完美。下载的文件保持相同的URL并附加原始名称。文件下载后如何保持相同的文件名?
$file = 'https://drive.google.com/uc?id=0B475ByfcR9n4a1JMVEZxQno2Tmc';
download($file);
function download($url) {
set_time_limit(0);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$r = curl_exec($ch);
curl_close($ch);
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', time()) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment;');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($r)); // provide file size
header('Connection: close');
echo $r;
}
答案 0 :(得分:1)
借鉴this answer here。基本上你想通过谷歌捕获Content-Disposition header(应包含文件名),并将其转发回客户端:
function download($url) {
set_time_limit(0);
$ch = curl_init();
$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// this function is called by curl for each header received
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$name = strtolower(trim($header[0]));
if (!array_key_exists($name, $headers))
$headers[$name] = [trim($header[1])];
else
$headers[$name][] = trim($header[1]);
return $len;
}
);
$r = curl_exec($ch);
curl_close($ch);
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', time()) . ' GMT');
header('Cache-Control: private', false);
header('Content-Type: application/force-download');
header('Content-Disposition: ' . $headers['content-disposition']);
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen($r)); // provide file size
header('Connection: close');
echo $r;
}