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程序设计有所帮助。

相关文章

PHP中时间加减函数strtotime用法分析

本文实例讲述了PHP中时间加减函数strtotime用法。分享给大家供大家参考,具体如下: 时间加减 <?php //获取本地 提取年份+1 $date=date("Y...

PHP引用返回用法示例

本文实例讲述了PHP引用返回的用法。分享给大家供大家参考,具体如下: 示例1: <?php $a = 1; function b(&$c) {   $c++;   re...

PHP基于phpqrcode类生成二维码的方法详解

PHP基于phpqrcode类生成二维码的方法详解

本文实例讲述了PHP基于phpqrcode类生成二维码的方法。分享给大家供大家参考,具体如下: 使用PHP语言生成二维码,还是挺有难度的,当然调用生成二维码图片的接口(比如:联图网htt...

简单的php 验证图片生成函数

复制代码 代码如下:<?php function yzm($name,$width,$height){ Header("Content-type: image/PNG"); sra...

生成静态页面的php函数,php爱好者站推荐

复制代码 代码如下:<?php  function CreateShtml()  {  ob_start("callback_CteateS...