PHP encapsulates cURL tool classes and application examples

  • 2021-12-12 04:02:20
  • OfStack

This article illustrates the PHP encapsulation of the cURL tool class. Share it for your reference, as follows:

CurlUtils tool classes:


<?php
/**
 * cURL Request tool class 
 */
class CurlUtils {
  private $ch;//curl Resource object 
  /**
   *  Construction method 
   * @param string $url  Requested address 
   * @param int $responseHeader  Whether response header information is required 
   */
  public function __construct($url,$responseHeader = 0){
    $this->ch = curl_init($url);
    curl_setopt($this->ch,CURLOPT_RETURNTRANSFER,1);// Set to return as a file stream 
    curl_setopt($this->ch,CURLOPT_HEADER,$responseHeader);// Sets whether the response header information is returned 
  }
  /**
   *  Destructional method 
   */
  public function __destruct(){
    $this->close();
  }
  /**
   *  Add a request header 
   * @param array $value  Request header 
   */
  public function addHeader($value){
    curl_setopt($this->ch, CURLOPT_HTTPHEADER, $value);
  }
  /**
   *  Send a request 
   * @return string  Data returned 
   */
  private function exec(){
    return curl_exec($this->ch);
  }
  /**
   *  Send get Request 
   * @return string  Data returned by request 
   */
  public function get(){
    return $this->exec();
  }
  /**
   *  Send post Request 
   * @param arr/string $value  Ready to send post Data of 
   * @param boolean $https  Whether it is https Request 
   * @return string     Data returned by request 
   */
  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);// Settings post Request 
    curl_setopt($this->ch,CURLOPT_POSTFIELDS,$value);
    return $this->exec();
  }
  /**
   *  Shut down curl Handle 
   */
  private function close(){
    curl_close($this->ch);
  }
}

Invoke the instance:

Face Recognition Interface Based on face + +


$curl = new CurlUtils("https://api-cn.faceplusplus.com/facepp/v3/detect");// Create curl Object 
$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'];// Prepare post Value of 
echo $curl->post($value);// Send a request 

For more readers interested in PHP related contents, please check the topics of this site: "php curl Usage Summary", "PHP Network Programming Skills Summary", "PHP Array (Array) Operation Skills Encyclopedia", "php String (string) Usage Summary", "PHP Data Structure and Algorithm Tutorial" and "json Format Data Operation Skills Summary in PHP"

I hope this article is helpful to everyone's PHP programming.


Related articles: