PHP curl 301 Moved Permanently(301永久迁移)的问题解决方法
微wx笑
2019-09-04【网络工具】
20
0关键字:
php curl
PHP curl 301 Moved Permanently(301永久迁移)的问题解决方法在终端中使用 curl https://static.liaoxuefeng.com/files/attachments/1259577026801664/l可以得到图片数据,但
PHP curl 301 Moved Permanently(301永久迁移)的问题解决方法
在终端中使用
curl https://static.liaoxuefeng.com/files/attachments/1259577026801664/l
可以得到图片数据,但在php中使用 curl 返回的却是:
<html> <head><title>301 Moved Permanently</title></head> <body bgcolor="white"> <center><h1>301 Moved Permanently</h1></center> <hr><center>nginx/1.14.0 (Ubuntu)</center> </body> </html>
解决方法
添加一行curl_setopt:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
意思是当遇到location跳转时,直接抓取跳转的页面。
下载方法代码:
function mkdirs($dir, $mode = 0777)
{
if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
if (!mkdirs(dirname($dir), $mode)) return FALSE;
return @mkdir($dir, $mode);
}
function download123($url, $path = 'images/')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$file = curl_exec($ch);
curl_close($ch);
$filename = pathinfo($url, PATHINFO_BASENAME);
if (stripos($filename, "?")){
$filename = strstr($filename, "?", true);
}
if (!stripos($filename, ".")){
$filename = $filename.".jpeg";
}
mkdirs($filename);
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
}本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/toolbox/newwork/2019-09-04/178.html



