curl模拟GET、POST、PUT、DELETE请求(PHP)

<?php

namespace App\Helpers\Tool;

use App\Helpers\Traits\SingletonTrait;
use Illuminate\Support\Facades\Log;

class Curl
{

    use SingletonTrait;
    protected $app_token;

    public function __construct(){
        $this->app_token = env('X_APPLICATION_TOKEN','3b*********************3116c693e3');
    }


    public function sendRequest($url, $data, $method = 'GET')
    {
        $headers = [
            'Content-Type: application/json',
            'X-Application-Token: ' . $this->app_token
        ];
        //启动一个CURL会话
        $handle = curl_init();
        switch ($method) {
            case 'GET':
                break;
            case 'POST':
                curl_setopt($handle, CURLOPT_POST, true);
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包
                break;
            case 'PUT':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'PUT');
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data); //设置请求体,提交数据包
                break;
            case 'DELETE':
                curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
                curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
                break;
        }
        // 要访问的地址
        curl_setopt($handle, CURLOPT_URL, $url);
        //获取的信息以文件流的形式返回
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        //是否显示返回的Header区域内容
        curl_setopt($handle, CURLOPT_HEADER, false);
        //设置请求头
        curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
        //从证书中检查SSL加密算法是否存在
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
        //对认证证书来源的检查
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        //执行操作
        $result = curl_exec($handle);
        //获取返回的状态码
        $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        //关闭CURL会话
        curl_close($handle);
        if ($code == 200) {
            return ['code' => 200, 'msg' => 'success','data' => $result];
        }elseif ($code == 400) {
            Log::info($url . '---> Bad Request');
            $result = json_decode($result,true);
            return ['code' => 1, 'msg' => 'Bad Request  ' . $result['message']];
        }elseif ($code == 401) {
            Log::info($url . '--->' . TOKEN_INVALID);
            return ['code' => 401, 'msg' => TOKEN_INVALID];
        }else {
            Log::info($url . '--->' . $result);
            return false;
        }
    }


}
© 版权声明
THE END
喜欢就支持一下吧
分享