PHP curl函數的使用樣本 類比curl請求

來源:互聯網
上載者:User

PHP有著很好的curl機制,但是用起來總是不那麼的令人滿意,因為它需要好幾步的操作和,好多難記的參數,這裡我將php的curl封裝了一下,使它不那麼的複雜:

 代碼如下 複製代碼

<?php
/**
 * php類比curl請求
 *
 * @param string $url     請求的url
 * @param string $method  請求的方法, 預設POST
 * @param array  $data    請求傳遞的資料
 * @param array  $header  請求設定的頭資訊
 * @param int    $head    是否列印頭資訊
 * @param int    $body    是否列印body資訊
 * @param int    $timeout 設定逾時時間
 *
 * @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 (!empty($header)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }
    switch ($method) {
    case 'POST':
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        break;
    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;
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.