在使用php curl获取网页内容有些网站提示405 method not allowed状态码了,这个问题我分析了出问题的网站是因为ipv6而导致了,所以我们只要简单的调整一下就可以解决这个问题了,下面一起来看看吧.
1.php curl ipv4使用例子,代码如下:
-
-
-
-
-
-
-
- public function web_http($url,$type,$ipresolve) {
-
- $header[] = "Accept: application/json";
- $header[] = "Accept-Encoding: gzip";
- $httptype = function_exists('curl_init');
- if (!$httptype) {
- $html = file_get_contents($url);
- } else {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
-
- curl_setopt($ch, CURLOPT_HEADER, 1);
-
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
-
- curl_setopt($ch, CURLOPT_NOBODY, 1);
-
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
-
- if($ipresolve=='ipv6') {
- curl_setopt($ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V6);
- }else{
- curl_setopt($ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
- }
-
- curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
- curl_setopt($ch,CURLOPT_ENCODING , "gzip");
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
-
- curl_setopt($ch,CURLOPT_DNS_CACHE_TIMEOUT,0);
-
- curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,15);
-
- curl_setopt($ch,CURLOPT_TIMEOUT,50);
-
- curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11');
- if($type=="https") {
-
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
-
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
- }
-
- $html = curl_exec($ch);
-
- $info = curl_getinfo($ch);
- curl_close($ch);
- }
- return $info;
- }
上面代码在ipv4是没有任何问题了,如果在了ipv6网站就会返回405 method not allowed状态码了,那么我们查看了php手册发现只要简单的修改一下即可.
以上为我编写的一个基本curl访问的方法,因为我这里需要通过使用IPv6的方式,所以加了相应的选项,相信大家能看的明白,平时经常用到的选项上面都有出现,大家根据需要摘取.
405/Method Not Allowed,表示不支持请求的方法,这个错误不常见.
导致403错误是要是由于curl默认是用post方式进行提交访问的,post方式在此域名下是没有权限的,如我在测试www.phpfensi.com的时候就出现了此问题,在我修改为get的方式,并且增加了header头后,即可正常访问,个人推测,或许是亚马逊那边基本上都是采用get的方式,才会被认为是人为的点击,对post做了相应屏蔽.
ipv6增加了如下代码:
-
- $header[] = "Accept: application/json";
- $header[] = "Accept-Encoding: gzip";
-
- curl_setopt( $ch, CURLOPT_HTTPHEADER, $header );
- curl_setopt($ch,CURLOPT_ENCODING , "gzip");
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
-
- curl -v www.phpfensi.com
IPV6下curl超时问题,代码如下:
- <?php
- $ch = curl_init();
- curl_setopt ($ch, CURLOPT_URL, $url);
- curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
-
- if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
- curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
- }
-
- curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
-
- curl_setopt ($ch, CURLOPT_TIMEOUT,$timeout*3);
- $file_contents = curl_exec($ch);
- curl_close($ch);
- ?>
注:curl_setopt($ch,CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4) 只有在php版本5.3及以上版本,curl版本7.10.8及以上版本时,以上设置才生效. |