网络工具您现在的位置是:首页 > 工具箱 > 网络工具

PHP curl 301 Moved Permanently(301永久迁移)的问题解决方法

<a href='mailto:'>微wx笑</a>的头像微wx笑 2019-09-04网络工具1212 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永久迁移)的问题解决方法nWu无知

在终端中使用 nWu无知

curl https://static.liaoxuefeng.com/files/attachments/1259577026801664/lnWu无知

可以得到图片数据,但在php中使用 curl 返回的却是:nWu无知

1
2
3
4
5
6
7
<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:nWu无知

1
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

意思是当遇到location跳转时,直接抓取跳转的页面。nWu无知

下载方法代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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);
}


nWu无知

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/toolbox/newwork/2019-09-04/178.html

很赞哦! (25) 有话说 (0)

文章评论