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

作者:webbc 时间:2023-10-18 11:57:36 

本文实例讲述了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);//发送请求

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

来源:https://blog.csdn.net/baochao95/article/details/55105748

标签:PHP,cURL,工具类
0
投稿

猜你喜欢

  • Java连接Sql数据库经常用到的操作

    2024-01-17 09:26:28
  • 利用Math.js解决JS计算小数精度丢失问题

    2024-04-29 13:44:04
  • Python中if __name__==‘__main__‘用法详情

    2021-07-18 02:38:20
  • Vue实现登录以及登出详解

    2023-07-02 16:59:51
  • Python进程池Pool应用实例分析

    2022-02-22 16:46:01
  • asp随机数 随机产生N位由数字和字母组成的密码

    2011-03-10 10:47:00
  • 程序员的八种境界,你在哪一境?

    2022-07-19 11:22:19
  • MySQL UPDATE delete 语句的速度

    2008-03-12 12:22:00
  • TCP关闭问题详细介绍

    2022-07-26 16:58:02
  • SQL Server中如何快速获取表的记录总数

    2008-12-05 15:59:00
  • MySQL模糊查找like通配符使用(小白入门篇)

    2024-01-17 19:02:53
  • Python 字符串操作详情

    2023-02-04 19:03:59
  • chr()函数参照表 chr13 chr10 chr34

    2009-09-03 13:22:00
  • sqlserver 动态创建临时表的语句分享

    2024-01-17 23:57:45
  • Python使用read_csv读数据遇到分隔符问题的2种解决方式

    2022-01-13 13:30:47
  • Python通用验证码识别OCR库之ddddocr验证码识别

    2021-05-16 22:55:00
  • python list转置和前后反转的例子

    2022-04-26 10:39:55
  • python 如何对logging日志封装

    2023-07-06 11:27:36
  • jsp输出九九乘法表的简单实例

    2023-07-12 01:26:31
  • python numpy中cumsum的用法详解

    2022-09-17 03:21:17
  • asp之家 网络编程 m.aspxhome.com