php从远程服务器下载文件,从设置标题的下载url
问题描述:
我试图用位于远程服务器上的php下载文件,但没有运气。我曾尝试使用fopen,get_file_contents,但没有任何工作。php从远程服务器下载文件,从设置标题的下载url
我传入一个下载URL,它不是确切的文件位置,它是文件的“下载URL”,然后强制浏览器下载。
因此,我认为这就是为什么文件fopen和file_get_contents失败,有人可以告诉我,我必须做什么从头文件下载文件设置为强制文件下载的URL。
任何帮助非常感谢!
答
虽然技术上不是重复的,这已被要求在此之前:How to get redirecting url link with php from bit.ly
您的问题是的file_get_contents不遵循重定向。查看解决方案的链接答案。
+0
谢谢你,你刚刚救了我可能几个小时更多的混乱和挫折!现在非常有意义。 – thrice801 2010-08-29 00:09:17
答
尽管你没有清楚地形成你的问题,我想我知道你的意思。 试试这个功能取自php.net评论
没有测试它,但它看起来不错,似乎遵循html标题重定向以及元和JavaScript重定向到文件。
<?php
/*==================================
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url)
@return array[0] content
array[1] array of response headers
==================================*/
function get_url($url, $javascript_loop = 0, $timeout = 5)
{
$url = str_replace("&", "&", urldecode(trim($url)));
$cookie = tempnam ("/tmp", "CURLCOOKIE");
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); # required for https urls
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
$content = curl_exec($ch);
$response = curl_getinfo($ch);
curl_close ($ch);
if ($response['http_code'] == 301 || $response['http_code'] == 302)
{
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
if ($headers = get_headers($response['url']))
{
foreach($headers as $value)
{
if (substr(strtolower($value), 0, 9) == "location:")
return get_url(trim(substr($value, 9, strlen($value))));
}
}
}
if ( (preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value)) &&
$javascript_loop < 5
)
{
return get_url($value[1], $javascript_loop+1);
}
else
{
return array($content, $response);
}
}
?>
请不要在任何情况下告诉我们“没有运气”和“不工作”的意思。它会带走我们猜测的乐趣! – 2010-08-28 23:05:25
哈哈我喜欢那个:D – 2010-08-28 23:09:53