php7 curl 发起post、get请求、post raw形式上传文件函数体封装

发起post、get请求

    /**
     * 发起请求
     * @param string $url
     * @param string|array $ret  请求体
     * 
     */
    private function http_req($url, $ret = '')
    {
    
    
        // 初始化
        $ch = curl_init();
        // 相关设置
        curl_setopt($ch, CURLOPT_URL, $url);
        // 不要请求头
        curl_setopt($ch, CURLOPT_HEADER, 0);
        // 请求结果不直接输出,而是字符串返回
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        # 设置请求超时时间 s
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        # 设置浏览器型号
        curl_setopt($ch, CURLOPT_HEADER, 'MSIE001');
        # 证书不检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        # 设置为post请求
        if ($ret != '') {
    
    
            // 开启post
            curl_setopt($ch, CURLOPT_POST, 1);
            // post请求数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $ret);
        }
        // 发起请求
        $data = curl_exec($ch);
        // 有无发送异常
        if (curl_errno($ch) > 0) {
    
    
            // 把错误发送给客户端
            echo curl_error($ch);
            $data = '';
        }
        // 关闭请求
        curl_close($ch);
        return $data;
    }

post raw形式上传文件

public function uploadF(string $url, string $filepath){
    
    
		/* 使用exec函数 */
        $command = 'curl -F media=@' . $filepath . ' "' . $url . '"';
        $retval = array();
        exec($command, $retval, $status);
        $params = array();
        $params = json_decode($retval[0], true);
        if ($status != 0) {
    
    
            $params = array(
                'errcode' => '-100',
                'errmsg' => '出错',
            );
        }
        return $params;
    }

猜你喜欢

转载自blog.csdn.net/weixin_42043407/article/details/116881085