PHP 封装CRUL GET 和 POST 的方法

2018-12-19  本文已影响0人  建博姓李

可用于做网络请求, 目前支持 GET/POST 且可使用参数

示例 1 : GET 请求

$url = 'http://127.0.0.1:8092/test/?id=1001&name=jianbo#top';

$params = [
  'time' => time(),
  'from' => 'test'
];

$rel = curl_get($url, $params);

print_r($rel);  

上面示例代码的输出结果来自:

http://127.0.0.1:8092/test/?time=1545195699&from=test&id=1001&name=jianbo

示例2: GET请求示例中

$url = 'http://127.0.0.1:8092';
$url = 'http://127.0.0.1:8092?';
$url = 'http://127.0.0.1:8092/test/';
$url = 'http://127.0.0.1:8092/test/?';
$url = 'http://127.0.0.1:8092/test/?id=1001&name=jianbo#top';

$params = [];

print(curl_get($url, $params));

示例 3 : POST 请求

$url = 'http://127.0.0.1:8092/test';

$params = [
  'time' => time(),
  'from' => 'test'
];

$rel = curl_post($url, $params);

print_r($rel);  

上面示例代码的输出结果来自:

http://127.0.0.1:8092/test/?time=1545195699&from=test&id=1001&name=jianbo

代码段: GET 请求

支持组合新参数,不支持 带#的地址

/**
* GET 请求
* @param  string  $url     请求目标链接地址
* @param  array   $params  参数
* @return mixed
* @author Jianboo
*/
function curl_get($url = '', $params = []) {
  // 组合新参数
  if (!empty($params)) {
    // 取出链接中的参数
    $url_parts= parse_url($url);

    $url_query = isset($url_parts['query']) ? $url_parts['query'] : '';

    // 组合新参数
    if ($url_query) {
      // 原链接参数
      $url_query_parts = explode('&', $url_query);

      $url_query_array = [];
      foreach ($url_query_parts as $value) {
        $item = explode('=', $value);
        $url_query_array[$item[0]] = $item[1];
      }
      if (!empty($url_query_array) && is_array($params)) $params = array_merge($params, $url_query_array);
    } else {
      // 原链接没有参数
    }
    $query = http_build_query($params);
    $url_parts = explode('?', $url);

    $url = $url_parts[0] . '?' . $query;
  } else{
    // 保持原链接不变
  }

  $options = array(
    CURLOPT_RETURNTRANSFER =>true,
    CURLOPT_HEADER =>false
  );
  $ch = curl_init($url);
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
           curl_close($ch);
           return $result;
}

代码段: POST 请求

/**
* POST 请求
* @param string $url
* @param array $params
* @example curl_post('http://yourdomain/target', ['timestamp' => 123456])
* @return mixed
* @author Jianboo
**/
function curl_post($url = '', $params =[]) {
  if (empty($url)) return false;
  $options = array(
    CURLOPT_RETURNTRANSFER =>true,
    CURLOPT_HEADER =>false,
    CURLOPT_POST =>true,
    CURLOPT_POSTFIELDS => $params
  );
  $ch = curl_init($url);
  curl_setopt_array($ch, $options);
  $result = curl_exec($ch);
  curl_close($ch);
  return $result;
}
上一篇下一篇

猜你喜欢

热点阅读