PHP封装cURL工具类与应用示例

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP封装cURL工具类。分享给大家供大家参考,具体如下:

CurlUtils工具类:

<?php
/**
 * cURL请求工具类
 */
class CurlUtils {
  private $ch;//curl资源对象
  /**
   * 构造方法
   * @param string $url 请求的地址
   * @param int $responseHeader 是否需要响应头信息
   */
  public function __construct($url,$responseHeader = 0){
    $this->ch = curl_init($url);
    curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,1);//设置以文件流的形式返回
    curl_setopt($this->ch,CURLOPT_HEADER,$responseHeader);//设置响应头信息是否返回
  }
  /**
   * 析构方法
   */
  public function __destruct(){
    $this->close();
  }
  /**
   * 添加请求头
   * @param array $value 请求头
   */
  public function addHeader($value){
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, $value);
  }
  /**
   * 发送请求
   * @return string 返回的数据
   */
  private function exec(){
    return curl_exec($this->ch);
  }
  /**
   * 发送get请求
   * @return string 请求返回的数据
   */
  public function get(){
    return $this->exec();
  }
  /**
   * 发送post请求
   * @param arr/string $value 准备发送post的数据
   * @param boolean $https 是否为https请求
   * @return string    请求返回的数据
   */
  public function post($value,$https=true){
    if($https){
      curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    }
    curl_setopt($this->ch,CURLOPT_POST,1);//设置post请求
    curl_setopt($this->ch,CURLOPT_POSTFIELDS,$value);
    return $this->exec();
  }
  /**
   * 关闭curl句柄
   */
  private function close(){
    curl_close($this->ch);
  }
}

调用实例:

face++的人脸识别接口

$curl = new CurlUtils("https://api-cn.faceplusplus.com/facepp/v3/detect");//创建curl对象
$value = ['api_key'=>'4Y7GS2sAPGEl-BtQlNw5Iqtq5jGOn87z','api_secret'=>'oQnwwJhS2mcm4vflKvgm972up9sLN8zj','image_url'=>'/zb_users/upload/202003/xjajod1xnnd.jpg','return_attributes'=>'gender,age,glass'];//准备post的值
echo $curl->post($value);//发送请求

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《PHP数据结构与算法教程》及《PHP中json格式数据操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP5新特性: 更加面向对象化的PHP

PHP处理对象部分的内核完全重新开发过,提供更多功能的同时也提高了性能。在以前版本的php中,处理对象和处理基本类型(数字,字符串)的方式是一样的。这种方式的缺陷是:当将对象赋值给一个变...

解析php入库和出库

数据放入数据库和取出来显示在页面需要注意什么 入库时 $str=addslashes($str); $sql=\"insert into `tab` (`content`) values...

将CMYK颜色值和RGB颜色相互转换的PHP代码

function hex2rgb($hex) { $color = str_replace('#','',$hex); $rgb = array('r' => hexdec(s...

php实现ip白名单黑名单功能

这个是一个检测ip是否非法的php函数,适应于白名单,黑名单功能开发,主要场景应用于:api来源限制,访问限制等. 复制代码 代码如下: /**  * 安全IP检测,支持IP段...

php 团购折扣计算公式

复制代码 代码如下: $price=$row['price']; //原价 $nowprice=$row['nowprice']; //现价 $jiesheng=$price-$nowp...