简单封装curl的get与post发送数据

简介:
<?php
header('content-type:text/html;charset=utf-8');

class Curl{
    private $ch;
    private $curl_url;
    function __construct($url=null){
        $this->ch = curl_init();
        $this->curl_url = $url;

    }

    /**post和get方式发送数据
     * @param $method string post或get方式
     * @param $vars 数据
     */
    function sendData( $vars = array(), $method = 'get',$url = ''){
        if($method != 'post' && $method != 'get'){
            exit('请输入有效的提交方式post或get');
            return false;
        }

        if(!empty($url)){
           $this->curl_url = $url;
            return false;
        }else if(empty($this->curl_url)){
            exit('url不能为空');
            return false;
        }

        if($method == 'post'){
            curl_setopt($this->ch, CURLOPT_POST, 1);
            curl_setopt($this->ch, CURLOPT_URL,$this->curl_url);
            if(is_array($vars) && !empty($vars)) {
                curl_setopt($this->ch, CURLOPT_POSTFIELDS, $vars);
            }
        }
        else if($method == 'get'){
            if(is_array($vars) && !empty($vars)) {
                $query = http_build_query($vars);
                curl_setopt($this->ch, CURLOPT_URL,$this->curl_url.'?'.$query);//将数组转化为字符串参数
            }else{
                curl_setopt($this->ch, CURLOPT_URL,$this->curl_url);//传递进来的url后可能有参数
            }
        }
        //执行命令
        $data = curl_exec($this->ch);
        //关闭URL请求
        curl_close($this->ch);
        return $data;
    }
}

$ch = new Curl('http://localhost/index.php');
$res = $ch->sendData(array('num'=>12), 'post');




目录
相关文章
|
6月前
|
缓存
POST 为什么会发送两次请求?
POST 为什么会发送两次请求?
414 0
|
4月前
|
人工智能 前端开发 安全
post为什么会发送两次请求?
post为什么会发送两次请求?
|
6月前
|
Cloud Native Go API
使用 cURL 发送 HTTP 请求: 深入探讨与示例
使用 cURL 发送 HTTP 请求: 深入探讨与示例
160 0
|
前端开发 JavaScript 容器
如何封装一个可取消的 HTTP 请求?
如何封装一个可取消的 HTTP 请求?
109 0
|
JSON 数据格式
QT 给http服务器发送GET/POST请求并接收返回值
QT 给http服务器发送GET/POST请求并接收返回值
QT 给http服务器发送GET/POST请求并接收返回值
|
JSON 数据格式
post发送json数据
post发送json数据
89 0
|
存储 JSON 缓存
GET/POST接收或发送数据的问题
GET/POST接收或发送数据的问题
|
Web App开发 程序员
使用ApiPost模拟发送get、post、delete、put等http请求
现在的模拟发送请求插件很多比如老外的postman等,但亲测咱们国内的 ApiPost 更好用一些,今天来分享如何使用ApiPost发送各种请求。