php使用file_get_contents 或者curl 發送get/post 請求 的方法總結


file_get_contents模擬GET/POST請求

模擬GET請求:

<?php
$data = array(
    'name'=>'zhezhao',
    'age'=>'23'
    );
$query = http_build_query($data);

$url = 'http://localhost/get.php';//這里一定要寫完整的服務頁面地址,否則php程序不會運行

$result = file_get_contents($url.'?'.$query);

echo $result;

模擬POST請求:

<?php
$data = array(
    'name'=>'zhezhao',
    'age'=>23
    ); 

$query = http_build_query($data); 

$options['http'] = array(
     'timeout'=>60,
     'method' => 'POST',
     'header' => 'Content-type:application/x-www-form-urlencoded',
     'content' => $query
    );

$url = "http://localhost/post.php";
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);

echo $result;
?>

 

curl模擬GET/POST請求

GET請求的參數

get傳遞參數和正常請求url傳遞參數的方式一樣

function get_info($card){

    $url ="http://www.sdt.com/api/White/CardInfo?cardNo=".$bank_card; 

    $ch = curl_init();
    //設置選項,包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    //執行並獲取HTML文檔內容
    $output = curl_exec($ch);
    //釋放curl句柄
    curl_close($ch);
    return $output;
}

HTTPS請求時要注意SSL驗證

function get_bankcard_info($bank_card){

    $url ="https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo=".$bank_card."&cardBinCheck=true";

    $ch = curl_init();

    //設置選項,包括URL
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//繞過ssl驗證
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    //執行並獲取HTML文檔內容
    $output = curl_exec($ch);

    //釋放curl句柄
    curl_close($ch);
    return $output;
}

post請求

/**
     * 模擬post進行url請求
     * @param string $url
     * @param array $param
     */
    function request_post($url = '', $param = []) {
        if (empty($url) || empty($param)) {
            return false;
        }
        $o = "";
        foreach ( $post_data as $k => $v ) 
        { 
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定網頁
        curl_setopt($ch, CURLOPT_HEADER, 0);//設置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求結果為字符串且輸出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//運行curl
        curl_close($ch);
        
        return $data;
    }    

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM