PHP使用CURL模拟POST和GET请求

在PHP中想要构造类似GET和POST请求,在一些APP或者等后端功能开发中是有这种需求。

在PHP语言当中有file_get_content()函数和 curl的支持。

PHP>5.3 的版本中默认两者都是开启的。

1、GET请求实现:

直接写代码了,就不再叙述,有需要的朋友直接 Ctrl+C+Ctrl+V 即可

<?php


function httpGET($target_url, $get_data = array()){
    $result = @file_get_content($target_url.'/?'.http_build_query($get_data));
    return $result;
}


/*
*    方法2
*/
function httpGET2($target_url, $get_data = array()){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $target_url.'/?'.http_build_query($get_data));
    curl_setopt($curl, CURLOPT_HEADER, 1);
     curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
     curl_close($curl);
    return $data;
}

?>

2、POST请求实现:

POST 请求没法儿使用 file_get_content() 函数来实现,所以只有使用 curl 方法来实现

<?php

function httpPOST($url , $post_data = array()){
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_HEADER, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post_data));
  $response = curl_exec($curl);
  curl_close($curl);
  return $response;
}
?>
发表评论 / Comment

用心评论~

金玉良言 / Appraise
免费SSR节点LV 2
2019-01-28 02:43
顶顶顶!!!学习了~

Warning: Cannot modify header information - headers already sent by (output started at /www/wwwroot/blog.dyboy.cn/content/templates/dyblog/footer.php:56) in /www/wwwroot/blog.dyboy.cn/include/lib/view.php on line 23