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;
    }    

 

猜你喜欢

转载自www.cnblogs.com/mverting/p/9325936.html