本文实例讲述了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'=>'http://avatar.csdn.net/9/7/5/1_baochao95.jpg','return_attributes'=>'gender,age,glass'];//准备post的值
echo $curl->post($value);//发送请求