美文网首页
PHP cURL详解,get、put、delete、post等,

PHP cURL详解,get、put、delete、post等,

作者: peanut___ | 来源:发表于2019-10-25 10:37 被阅读0次

curl是一种在命令行利用URL语法实现文件传输的工具
以下是一些简单curl功能的连贯操作方式实现
...
<hr />
...

<?php
class Mcurl
{
    public $ch;

    public function __construct()
    {
        $this->ch = curl_init();
    }


    private function init($url)
    {
        //初始化CURL句柄
        curl_setopt($this->ch, CURLOPT_URL, $url);//设置请求的URL
        // curl_setopt($this->ch, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
        
        $header[] = "Content-Type:application/json;charset=utf-8";
        if(! empty($header))
        {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);//设置 HTTP 头字段的数组。格式: array('Content-type: text/plain', 'Content-length: 100') 
        }

        return $this;
    }

    /**
     * 如果需要登录
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    public function auth($username, $password)
    {
        // 传递一个连接中需要的用户名和密码,格式为:"[username]:[password]"。
        curl_setopt($this->ch, CURLOPT_USERPWD, "{$username}:{$password}");
    }


    public function post(array $params)
    {
        // curl_setopt($this->ch, CURLOPT_POST,true);//TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
        // curl_setopt($this->ch, CURLOPT_NOBODY, true);//TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 请求时,使用自定义的 Method 来代替"GET"或"HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET","POST","CONNECT"等等;
        //设置提交的信息
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));//全部数据使用HTTP协议中的 "POST" 操作来发送。

        return $this->close();
    }


    public function head()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "HEAD");

        return $this->close();
    }


    public function delete()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE");

        return $this->close();
    }


    public function put($params = [])
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));

        return $this->close();
    }


    public function get()
    {
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);//TRUE 时会设置 HTTP 的 method 为 GET,由于默认是 GET,所以只有 method 被修改时才需要这个选项。 

        return $this->close();
    }


    /**
     * 执行并关闭
     * @return [type] [description]
     */
    private function close()
    {
        $data = curl_exec($this->ch);//执行预定义的CURL
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);//获取http返回值,最后一个收到的HTTP代码
        curl_close($this->ch);//关闭cURL会话
        $res = json_decode($data, true);

        return $res;
    }


    /**
     * 是否是https
     * @return [type] [description]
     */
    public function https()
    {
        //SSL验证
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求时要设置为false 不验证证书和hosts  FALSE 禁止 cURL 验证对等证书(peer's certificate), 自cURL 7.10开始默认为 TRUE。从 cURL 7.10开始默认绑定安装。 
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)。
        
        return $this;
    }


    /**
     * 请求时间
     * @param  integer $timeout [description]
     * @return [type]           [description]
     */
    public function out($timeout = 30)
    {
        //请求时间
        curl_setopt ($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);//设置连接等待时间

        return $this;
    }


    public function __call($method, $params)
    {
        if (method_exists($this, $method))
        {
            return $this->$method(...$params);
        }
    }


    public static function __callStatic($method, $params)
    {
        $Mcurl = new Mcurl;

        if (method_exists($Mcurl, $method))
        {
            return $Mcurl->$method(...$params);
        }
    }
}

// $url = 'x';
// $a = Mcurl::init($url)->get();
// print_r($a);

附上已model形式封装的curl

<?php
namespace App\Model\Base;

class Curl
{
    private $ch;  // curl对象
    public $url;  // 地址
    public $port;  // 端口
    public $route;  // 路由
    public $header = [];  // header
    public $returnTransfer = 1; // 转化字符串
    public $json = true;

    public function __construct()
    {
        if ($this->url)
        {
            $this->setUrl();
            $this->init();
        }
    }

    private function setUrl()
    {
        $this->url = config($this->url);
        $this->port && $this->url .= ':' . config($this->port);
        $this->route && $this->url .= '/' . $this->route;
    }

    /**
     * 自定义url
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    private function customUrl($url)
    {
        $this->url = $url;
        $this->init();

        return $this;
    }

    private function init()
    {
        $this->ch = curl_init();
        //初始化CURL句柄
        curl_setopt($this->ch, CURLOPT_URL, $this->url);//设置请求的URL
        // curl_setopt($this->ch, CURLOPT_HEADER, false);// 不要http header 加快效率
        curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, $this->returnTransfer); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
        
        $this->header[] = "Content-Type:application/json;charset=utf-8";
        if(! empty($this->header))
        {
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->header);//设置 HTTP 头字段的数组。格式: array('Content-type: text/plain', 'Content-length: 100') 
        }

        return $this;
    }

    /**
     * 如果需要登录
     * @param  [type] $username [description]
     * @param  [type] $password [description]
     * @return [type]           [description]
     */
    private function auth($username, $password)
    {
        // 传递一个连接中需要的用户名和密码,格式为:"[username]:[password]"。
        curl_setopt($this->ch, CURLOPT_USERPWD, "{$username}:{$password}");

        return $this;
    }


    private function post($params = [])
    {
        // curl_setopt($this->ch, CURLOPT_POST,true);//TRUE 时会发送 POST 请求,类型为:application/x-www-form-urlencoded,是 HTML 表单提交时最常见的一种。
        // curl_setopt($this->ch, CURLOPT_NOBODY, true);//TRUE 时将不输出 BODY 部分。同时 Mehtod 变成了 HEAD。修改为 FALSE 时不会变成 GET。
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "POST");//HTTP 请求时,使用自定义的 Method 来代替"GET"或"HEAD"。对 "DELETE" 或者其他更隐蔽的 HTTP 请求有用。 有效值如 "GET","POST","CONNECT"等等;
        //设置提交的信息 JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));//全部数据使用HTTP协议中的 "POST" 操作来发送。

        return $this->close();
    }


    private function head()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "HEAD");

        return $this->close();
    }


    private function delete()
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "DELETE");

        return $this->close();
    }


    private function put($params = [])
    {
        curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, json_encode($params, 320));

        return $this->close();
    }


    private function get()
    {
        curl_setopt($this->ch, CURLOPT_HTTPGET, true);//TRUE 时会设置 HTTP 的 method 为 GET,由于默认是 GET,所以只有 method 被修改时才需要这个选项。 

        return $this->close();
    }


    /**
     * 执行并关闭
     * @return [type] [description]
     */
    private function close()
    {
        $data = curl_exec($this->ch);//执行预定义的CURL
        $status = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);//获取http返回值,最后一个收到的HTTP代码
        curl_close($this->ch);//关闭cURL会话

        if (! $this->json) return $data;
        $res = json_decode($data, true);

        return $res;
    }


    /**
     * 是否是https
     * @return [type] [description]
     */
    private function https()
    {
        //SSL验证
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求时要设置为false 不验证证书和hosts  FALSE 禁止 cURL 验证对等证书(peer's certificate), 自cURL 7.10开始默认为 TRUE。从 cURL 7.10开始默认绑定安装。 
        curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);//检查服务器SSL证书中是否存在一个公用名(common name)。
        
        return $this;
    }


    /**
     * 请求时间
     * @param  integer $timeout [description]
     * @return [type]           [description]
     */
    private function out($timeout = 30)
    {
        //请求时间
        curl_setopt ($this->ch, CURLOPT_CONNECTTIMEOUT, $timeout);//设置连接等待时间

        return $this;
    }

    private function error($message = 'error')
    {
        return $message;
    }

    public function __call($method, $params)
    {
        if (method_exists($this, $method))
        {
            return $this->$method(...$params);
        }
    }


    public static function __callStatic($method, $params)
    {
        $class = static::class;
        $Mcurl = new $class;
        
        if (method_exists($Mcurl, $method))
        {
            return $Mcurl->$method(...$params);
        }
    }
}

1 调用config url

<?php

namespace App\Model\Expert\Api;

class PCAP extends \App\Model\Base\Curl
{
    public $url = 'xx'; // 链接
    public $port = 'xx';  // 端口
    public $route = 'xx';  // 路由

    public static function getSizeAndCountOnPCAP($key, $direction)
    {
        $array = [
            "para" => [
                "type" => "querypacketinfo",
                "key" => $key,
                "direction" => $direction
            ]
        ];
        
        if (($temp = self::post($array)) && isset($temp['data']))
        {
            return explode('-', $temp['data']);
        }

        // count-size
        return [0, 0];
    }
}

2 自定义url

<?php

namespace App\Model\Expert\Api;

class PCAPShow extends \App\Model\Base\Curl
{
    public $url = ''; // 链接
    public $port = '';  // 端口
    public $route = '';  // 路由
    public $json = false;  // 关闭json转换

    public static function getShowData($url)
    {
        $data = self::customUrl($url)->get();

        return $data;
    }
}

相关文章

网友评论

      本文标题:PHP cURL详解,get、put、delete、post等,

      本文链接:https://www.haomeiwen.com/subject/apqsvctx.html