1. 程式人生 > >php封裝curl,模擬POST和GET請求HTTPS請求

php封裝curl,模擬POST和GET請求HTTPS請求

<?php

/**
 * @title 封裝代理請求
 * @author victor
 **/
class ApiRequest {

  /**
   * curl提交資料
   * @param String $url 請求的地址
   * @param Array $header 自定義的header資料
   * @param Array $content POST的資料
   * @return String
   */
   public function toCurl($url, $header, $content)
   {
       $ch = curl_init();
       
if(substr($url,0,5)=='https'){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 跳過證書檢查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); // 從證書中檢查SSL加密演算法是否存在 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉 } curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt(
$ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content)); $response = curl_exec($ch); if($error=curl_error($ch)){ die($error); } curl_close(
$ch); return $response; } /** * @desc GET請求 **/ public function curl_get($url, array $params = array(), $timeout = 5) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); return $file_contents; } /** * @desc POST請求 **/ public function curl_post($url, array $params = array(), $timeout) { $ch = curl_init();//初始化 curl_setopt($ch, CURLOPT_URL, $url);//抓取指定網頁 curl_setopt($ch, CURLOPT_HEADER, 0);//設定header curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果為字串且輸出到螢幕上 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_POST, 1);//post提交方式 curl_setopt($ch, CURLOPT_POSTFIELDS, $params); $data = curl_exec($ch);//執行curl curl_close($ch); return ($data); } /** * @desc https 請求 **/ public function curl_get_https($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11'); $res = curl_exec($ch); $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return $res; } } ?>

呼叫:

public function proxyTest()
 {
     $ApiReq = new ApiRequest();

     //該網站的介面地址;
     $url = 'https://www.xxx.com/ajax/fx.do';

     //模擬header內容
     $header = array(
     'Host: www.domain.com',
     'Origin: https://www.domain.com',
     'Referer: https://www.domain.com/',
     'User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
     'X-Requested-With: XMLHttpRequest'
     );
     // post請求引數
     $content = array();

     //curl模擬提交
     $response = $ApiReq -> toCurl($url, $header, $content);
     $response = json_decode($response,true);
     return $response;
 }