Home  >  Article  >  Backend Development  >  Example of http request encapsulation implemented by php

Example of http request encapsulation implemented by php

高洛峰
高洛峰Original
2017-03-21 15:56:122630browse

The example in this article describes PHP's http request encapsulation. Share it with everyone for your reference, the details are as follows:

/**
* 发送HTTP请求方法,目前只支持CURL发送请求
* @param string $url  请求URL
* @param array $params 请求参数
* @param string $method 请求方法GET/POST
* @return array $data  响应数据
*/
protected function http($url, $params, $method = 'GET', $header = array(), $multi = false) {
    $opts = array(CURLOPT_TIMEOUT => 30, CURLOPT_RETURNTRANSFER => 1, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, CURLOPT_HTTPHEADER => $header);
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)) {
      case 'GET' :
        $opts[CURLOPT_URL] = $url . '&' . http_build_query($params);
        dump($opts[CURLOPT_URL]);
        break;
      case 'POST' :
        //判断是否传输文件
        $params = $multi ? $params : http_build_query($params);
        $opts[CURLOPT_URL] = $url;
        dump($opts[CURLOPT_URL]);
        $opts[CURLOPT_POST] = 1;
        $opts[CURLOPT_POSTFIELDS] = $params;
        break;
      default :
        throw new Exception('不支持的请求方式!');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error)
      throw new Exception('请求发生错误:' . $error);
    return $data;
}

I hope this article will be helpful to everyone in PHP program design.

For more articles related to http request encapsulation examples implemented by PHP, please pay attention to the PHP Chinese website!

Related articles:

How to get the header information of http request in PHP

Steps to implement how to get the header information of http request in PHP

php HTTP request class, supports GET, POST, Multipart/form-data

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn