php curl基本使用

本文介绍了在API开发中如何利用PHP的curl库模拟HTTP请求,特别是在Laravel框架下的一些具体实现,包括源码展示和调用方法。
摘要由CSDN通过智能技术生成

1、背景:
近来做API开发,经常使用到curl模拟http请求(不要太依赖guzzle)。故整理了一下,具体代码如下!在laravel中写的,请留意部分larval特有属性。

2、源码:

<?php
class HttpCurl
{
   
    public $ch = null; // curl handle
    private $headers = array();// request header
    private $proxy = null; // http proxy
    private $timeout = 5;    // connnect timeout
    private $httpParams = null;
    public $error_info;


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

    public function setHeader($header)
    {
   
        if (is_array($header)) {
   
            curl_setopt($this->ch, CURLOPT_HTTPHEADER, $header);
        }

        // 'Authorization: Basic bGVhbm1vYmk6YjkwN2ViNTczODllNDI5Zjg1Njg2OTc2ZGNjMTQzNzQ='

        return $this;
    }

    public function setTimeout($time)
    {
   
        // 不能小于等于0
        if ($time <= 0) {
   
            $time = 5;
        }
        //只需要设置一个秒的数量就可以
        curl_setopt($this->ch, CURLOPT_TIMEOUT, $time);

        return $this;
    }

    public function setProxy($proxy)
    {
   
        if ($proxy) {
   
            curl_setopt($this->ch, CURLOPT_PROXY, $proxy);
        }

        return $this;
    }

    public function setProxyPort($port)
    {
   
        if (is_int($port)) {
   
            curl_setopt($this->ch, CURLOPT_PROXYPORT, $port);
        }

        return $this;
    }

    public function setReferer($referer = "")
    {
   
        if (!empty($referer))
            curl_setopt($this->ch, CURLOPT_REFERER, $referer);

        return $this;
    }

    public function setUserAgent($agent = "")
    {
   
        if ($agent) {
   
            // 模拟用户使用的浏览器
            curl_setopt($this->ch, CURLOPT_USERAGENT, $agent);
        }

        return $this;
    }

    public function showResponseHeader($show)
    {
   
        curl_setopt($this->ch, CURLOPT_HEADER, $show);

        return<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值