如何在PHP代碼中使用HTTP代理IP。
以下代碼主要圍繞第一次接觸HTTP代理IP的PHP新手來寫。(步驟注釋清晰)
直接把下面示例代碼中的HTTP代理API,替換成你后臺生成的代理API鏈接,就可以跑起來了。
以下是一個示例代碼,只是一個基礎(chǔ)的演示,具體的代碼還是要根據(jù)你業(yè)務(wù)的實(shí)際情況去寫的。
示例代碼中的HTTP代理IP,我使用的是華益云的HTTP代理,注冊就能白嫖1萬個高匿爬蟲IP,有效期是一年,對于調(diào)試代碼來說這個時間是非常的友好。(步驟注釋清晰)
華益云-企業(yè)級HTTP爬蟲代理IP供應(yīng)商-點(diǎn)我免費(fèi)領(lǐng)取示例代碼demo中同款10000個高匿IP
打開代理API,獲取里面的IP,使用IP訪問目標(biāo)網(wǎng)站,其實(shí)代碼中就是執(zhí)行這個過程而已,然后加了幾個錯誤判斷有助于代碼的穩(wěn)定運(yùn)行。(步驟注釋清晰)
"); $content = requestGet($url, $userAgent, $px); break; }catch(Exception $e){ echo($e); if (count($outPutProxy)==0){ // 判斷下代理還有沒有,沒有的了就重新獲取下 $outPutProxy = getProxy($proxyUrl, $userAgent); } } } echo(" "); echo(" "); // htmlspecialchars 使用此函數(shù)不會渲染為網(wǎng)頁 // 這便是響應(yīng)內(nèi)容了 echo(htmlspecialchars($content)); } function getProxy($proxyUrl, $userAgent){ $proxyIps = ""; $outPutProxy = []; try{ $proxyIps = requestGet($proxyUrl, $userAgent, array()); # {"code":3002,"data":[],"msg":"error!用戶名或密碼錯誤","success":false} if (strpos($proxyIps, "{", 0) > -1){ throw new Exception($proxyIps); } $eachIps = explode("\r\n", $proxyIps); foreach ($eachIps as $value){ $currentIp = explode(":", $value); array_push($outPutProxy, array( $currentIp[0], $currentIp[1])); } }catch(Exception $e){ echo($e); } // var_dump($outPutProxy); echo("總共獲取了"); echo(count($outPutProxy)); echo("個代理"); echo(" "); return $outPutProxy; } function requestGet($url, $userAgent, $proxy){ $headerArray = array("User-Agent:$userAgent;"); $ch = curl_init(); # $headerArray =array("Content-type:application/json;","Accept:application/json"); // 設(shè)置要請求的url curl_setopt($ch, CURLOPT_URL, $url); // 設(shè)置整體最大超時時間 curl_setopt($ch, CURLOPT_TIMEOUT, 5); // 設(shè)置最大連接超時時間 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); // 設(shè)置不驗(yàn)證ssl證書 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 設(shè)置不驗(yàn)證ssl證書 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 這樣設(shè)置的話我們可以拿到響應(yīng)內(nèi)容并且可以保存在一個變量里 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 設(shè)置請求頭,比如 user-agent,cookie,referer啥的 curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray); if (count($proxy) != 0){ // 設(shè)置代理 // curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1"); // curl_setopt($ch, CURLOPT_PROXYPORT, "10809"); curl_setopt($ch, CURLOPT_PROXY, $proxy[0]); curl_setopt($ch, CURLOPT_PROXYPORT, $proxy[1]); } // 執(zhí)行發(fā)送請求 $result = curl_exec($ch); curl_close($ch); return $result; } main() ?>
或者直接百度搜索:華益云HTTP代理
審核編輯:湯梓紅
-
HTTP
+關(guān)注
關(guān)注
0文章
513瀏覽量
31842 -
代碼
+關(guān)注
關(guān)注
30文章
4858瀏覽量
69553 -
PHP
+關(guān)注
關(guān)注
0文章
454瀏覽量
26923
發(fā)布評論請先 登錄
相關(guān)推薦
評論