如果某个域名对应多个ip,即有多台服务器。如何通过curl来访问指定一台服务器的url信息了。我们知道一般使用curl获取url信息的代码如下
1 2 3 4 5 6 7 | $url = "http://www.phper163.com/" ; $ch =curl_init(); curl_setopt( $ch ,CURLOPT_URL, $url ); curl_setopt( $ch ,CURLOPT_TIMEOUT,5); curl_setopt( $ch ,CURLOPT_RETURNTRANSFER,1); $content =curl_exec( $ch ); echo $content ; |
如果想访问39.99.204.74这个ip服务器的内容了,可以将请求url中域名部分改用ip方式,并加上Host请求头信息。具体示例代码如下
1 2 3 4 5 6 7 8 | $url = 'http://39.99.204.74/index.php' ; $ch =curl_init(); curl_setopt( $ch ,CURLOPT_URL, $url ); curl_setopt( $ch ,CURLOPT_TIMEOUT,5); curl_setopt( $ch ,CURLOPT_RETURNTRANSFER,1); curl_setopt( $ch ,CURLOPT_HTTPHEADER, array ( "Host: www.phper163.com" )); $content =curl_exec( $ch ); echo $content ; |
具体我们可以封装一个函数,方便调取,少量改动代码
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 35 | function curlHttpRequest( $url , $postdata =null, $httpheader = array (), $ip =null){ $ch = curl_init(); $timeout = 5; if (! is_array ( $httpheader )){ $httpheader = array ();} //如果ip指定,则请求url中域名变更为对应ip,并且设置 $httpheader变量值 if ( $ip ){ $urlArr = parse_url ( $url ); $url = str_replace ( $urlArr [ 'host' ], $ip , $url ); array_unshift ( $httpheader , 'Host: ' . $urlArr [ 'host' ]); } curl_setopt( $ch ,CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' ); curl_setopt( $ch , CURLOPT_URL, $url ); curl_setopt( $ch , CURLOPT_RETURNTRANSFER, 1); curl_setopt( $ch , CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $ch , CURLOPT_TIMEOUT, $timeout ); if ( $postdata ){ curl_setopt ( $ch , CURLOPT_POST, true); curl_setopt ( $ch , CURLOPT_POSTFIELDS, $postdata ); } if ( $httpheader ){ curl_setopt( $ch , CURLOPT_HTTPHEADER, $httpheader ); } $contents = curl_exec( $ch ); $status = curl_getinfo( $ch ); if ( $status [ 'http_code' ] == 200){ return $contents ; } return false; } |
友情提示:垃圾评论一律封号...