PHP curl函數(shù)是可以模仿用戶進(jìn)行訪問頁(yè)面了,下面來給各位介紹一下工作中常用的到的PHP curl函數(shù)示例.
PHP有著很好的curl機(jī)制,但是用起來總是不那么的令人滿意,因?yàn)樗枰脦撞降牟僮骱?好多難記的參數(shù),這里我將php的curl封裝了一下,使它不那么的復(fù)雜,代碼如下:
- <?php
- /**
- * php模擬curl請(qǐng)求
- *
- * @param string $url 請(qǐng)求的url
- * @param string $method 請(qǐng)求的方法, 默認(rèn)POST
- * @param array $data 請(qǐng)求傳遞的數(shù)據(jù)
- * @param array $header 請(qǐng)求設(shè)置的頭信息
- * @param int $head 是否打印頭信息
- * @param int $body 是否打印body信息
- * @param int $timeout 設(shè)置超時(shí)時(shí)間
- *
- * @return array
- */
- function curl($url,$method="POST",$data=array(),$header=array(),$head=0,$body=0,$timeout = 30)
- {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- if (strpos($url, "https") !== false ) {
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
- if (isset($_SERVER['HTTP_USER_AGENT'])) {
- curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
- }
- }
- if (!emptyempty($header)) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- }
- switch ($method) {
- case 'POST':
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
- break; //開源軟件:Vevb.com
- case 'GET':
- break;
- case 'PUT':
- curl_setopt($ch, CURLOPT_PUT, 1);
- curl_setopt($ch, CURLOPT_INFILE, '');
- curl_setopt($ch, CURLOPT_INFILESIZE, 10);
- break;
- case 'DELETE':
- curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
- break;
- default:
- break;
- }
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, $head);
- curl_setopt($ch, CURLOPT_NOBODY, $body);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
- $rtn = curl_exec($ch); //獲得返回
- if (curl_errno($ch)) {
- echo 'Errno'.curl_error($ch);//捕抓異常
- }
- curl_close($ch);
- return $rtn;
- }
- ?>
新聞熱點(diǎn)
疑難解答