PHP 利用curl_init發起http請求模仿登入

來源:互聯網
上載者:User

備忘:使用curl_init函數,必須要開啟這個php擴充。

1.開啟php.ini,開啟extension=php_curl.dll
2.檢查php.ini的extension_dir值是哪個目錄,檢查有無php_curl.dll,沒有的請下載php_curl.dll,再把php目錄中的libeay32.dll,ssleay32.dll拷到c:/windows/system32裡面。

發起http請求

 代碼如下 複製代碼

function _http_curl_post($url,$data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);
    curl_setopt($ch, CURLOPT_TIMEOUT,4);
         
    if($data){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "value=".json_encode($data));  //請求參數轉為json格式
    }
    curl_setopt($ch, CURLOPT_HEADER, false);
    $string = curl_exec($ch);
    curl_close($ch);
    return $string;
}

調用方法

 代碼如下 複製代碼

$params = array();
$params['id']       = 1
$params['web_name']   = '好指令碼';
$params['web_url']    = 'http://www.111cn.net/';
$params['web_miaoshu']      = '指令碼編程樣本';
$data = _curl_post($url,$params);
$arr =json_decode($data);

除了http請求之外還有一個https的請求,上次我做人人網的一鍵登入,它的介面就是https的url,使用上面的函數,最終報錯。如果您也遇到這樣的問題,你可以參考下面方法解決。

https請求樣本

 代碼如下 複製代碼

function _https_curl_post($url, $vars) 

    foreach($vars as $key=>$value)
    {
        $fields_string .= $key.'='.$value.'&' ;
    } 
    $fields_string = substr($fields_string,0,(strlen($fields_string)-1)) ;
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL,$url); 
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  // this line makes it work under https
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_POST, count($vars) );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);     
    $data = curl_exec($ch);        
    curl_close($ch);  
       
    if ($data)
    {
        return $data;
    }
    else
    {
        return false;
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.