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

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');




你可能感兴趣的:(简单封装curl的get与post发送数据)