国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
php creates a cross-platform restfule interface based on curl extension, phpcurlrestfule
Home Backend Development PHP Tutorial PHP makes a cross-platform restfule interface based on curl extension, phpcurlrestfule_PHP tutorial

PHP makes a cross-platform restfule interface based on curl extension, phpcurlrestfule_PHP tutorial

Jul 13, 2016 am 09:54 AM
curl extension php interface

php creates a cross-platform restfule interface based on curl extension, phpcurlrestfule

restfule interface
Applicable platforms: Cross-platform
Depends on: curl extension
git: https://git.oschina.net/anziguoer/restAPI

ApiServer.php

<&#63;php
/**
 * @Author: yangyulong
 * @Email : anziguoer@sina.com
 * @Date:  2015-04-30 05:38:34
 * @Last Modified by:  yangyulong
 * @Last Modified time: 2015-04-30 17:14:11
 */
 
class apiServer
{
  /**
   * 客戶端請(qǐng)求的方式
   * @var string
   */
  private $method = '';
 
  /**
   * 客戶端發(fā)送的數(shù)據(jù)
   * @var [type]
   */
  protected $param;
 
  /**
   * 要操作的資源
   * @var [type]
   */
  protected $resourse;
 
  /**
   * 要操作的資源id
   * @var [type]
   */
  protected $resourseId;
 
 
  /**
   * 構(gòu)造函數(shù), 獲取client 請(qǐng)求的方式,以及傳輸?shù)臄?shù)據(jù)
   * @param object 可以自定義傳入的對(duì)象
   */
  public function __construct()
  {
    //首先對(duì)客戶端的請(qǐng)求進(jìn)行驗(yàn)證
    $this->authorization();
 
    $this->method = strtolower($_SERVER['REQUEST_METHOD']);
 
    //所有的請(qǐng)求都是pathinfo模式
    $pathinfo = $_SERVER['PATH_INFO'];
 
    //將pathinfo數(shù)據(jù)信息映射為實(shí)際請(qǐng)求方法
    $this->getResourse($pathinfo);
 
    //獲取傳輸?shù)木唧w參數(shù)
    $this->getData();
 
    //執(zhí)行響應(yīng)
    $this->doResponse();
  }
 
  /**
   * 根據(jù)不同的請(qǐng)求方式,獲取數(shù)據(jù)
   * @return [type]
   */
  private function doResponse(){
    switch ($this->method) {
      case 'get':
        $this->_get();
        break;
      case 'post':
        $this->_post();
        break;
      case 'delete':
        $this->_delete();
        break;
      case 'put':
        $this->_put();
        break;
      default:
        $this->_get();
        break;
    }
  }
 
  // 將pathinfo數(shù)據(jù)信息映射為實(shí)際請(qǐng)求方法
  private function getResourse($pathinfo){
 
    /**
     * 將pathinfo數(shù)據(jù)信息映射為實(shí)際請(qǐng)求方法
     * GET /users: 逐頁列出所有用戶;
     * POST /users: 創(chuàng)建一個(gè)新用戶;
     * GET /users/123: 返回用戶為123的詳細(xì)信息;
     * PUT /users/123: 更新用戶123;
     * DELETE /users/123: 刪除用戶123;
     *
     * 根據(jù)以上規(guī)則,將pathinfo第一個(gè)參數(shù)映射為需要操作的數(shù)據(jù)表,
     * 第二個(gè)參數(shù)映射為操作的id
     */
     
    $info = explode('/', ltrim($pathinfo, '/'));
    list($this->resourse, $this->resourseId) = $info;
  }
 
  /**
   * 驗(yàn)證請(qǐng)求
   */
  private function authorization(){
    $token = $_SERVER['HTTP_CLIENT_TOKEN'];
    $authorization = md5(substr(md5($token), 8, 24).$token);
    if($authorization != $_SERVER['HTTP_CLIENT_CODE']){
      //驗(yàn)證失敗,輸出錯(cuò)誤信息給客戶端
      $this->outPut($status = 1);
    }
  }
 
  /**
   * [getData 獲取傳送的參數(shù)信息]
   * @param [type] $pad [description]
   * @return [type]   [description]
   */
  private function getData(){
    //所有的參數(shù)都是get傳參
    $this->param = $_GET;
  }
 
  /**
   * 獲取資源操作
   * @return [type] [description]
   */
  protected function _get(){
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }  
 
  /**
   * 新增資源操作
   * @return [type] [description]
   */
  protected function _post(){
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
 
  /**
   * 刪除資源操作
   * @return [type] [description]
   */
  protected function _delete(){
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
 
  /**
   * 更新資源操作
   * @return [type] [description]
   */
  protected function _put(){
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
 
  /**
   * 出入服務(wù)端返回的數(shù)據(jù)信息 json格式
   */
  public function outPut($stat, $data=array()){
    $status = array(
      //0 狀態(tài)表示請(qǐng)求成功
      0 => array(
        'code' => 1,
        'info' => '請(qǐng)求成功',
        'data' =>$data
      ),
      //驗(yàn)證失敗
      1 => array(
        'code' => 0,
        'info' => '請(qǐng)求不合法'
      )
    );
 
    try{
      if(!in_array($stat, array_keys($status))){
        throw new Exception('輸入的狀態(tài)碼不合法');
      }else{
        echo json_encode($status[$stat]);
      }
    }catch (Exception $e){
      die($e->getMessage());
    }
  }
}

ApiClient.php

<&#63;php
 
/**
 * Created by PhpStorm.
 * User: anziguoer@sina.com
 * Date: 2015/4/29
 * Time: 12:36
 * link: http://www.ruanyifeng.com/blog/2014/05/restful_api.html [restful設(shè)計(jì)指南]
 */
/*** * * * * * * * * * * * * * * * * * * * * * * * * * ***\
 * 定義路由的請(qǐng)求方式                  *
 *                            *
 * $url_model=0                     *
 * 采用傳統(tǒng)的URL參數(shù)模式                 *
 * http://serverName/appName/&#63;m=module&a=action&id=1   *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * PATHINFO模式(默認(rèn)模式)               *
 * 設(shè)置url_model 為1                   *
 * http://serverName/appName/module/action/id/1/     *
 ** * * * * * * * * * * * * * * * * * * * * * * * * * * **
*/
class restClient
{
  //請(qǐng)求的token
  const token='yangyulong';
 
  //請(qǐng)求url
  private $url;
   
  //請(qǐng)求的類型
  private $requestType;
   
  //請(qǐng)求的數(shù)據(jù)
  private $data;
   
  //curl實(shí)例
  private $curl;
 
  public $status;
 
  private $headers = array();
  /**
   * [__construct 構(gòu)造方法, 初始化數(shù)據(jù)]
   * @param [type] $url     請(qǐng)求的服務(wù)器地址
   * @param [type] $requestType 發(fā)送請(qǐng)求的方法
   * @param [type] $data    發(fā)送的數(shù)據(jù)
   * @param integer $url_model  路由請(qǐng)求方式
   */
  public function __construct($url, $data = array(), $requestType = 'get') {
     
    //url是必須要傳的,并且是符合PATHINFO模式的路徑
    if (!$url) {
      return false;
    }
    $this->requestType = strtolower($requestType);
    $paramUrl = '';
    // PATHINFO模式
    if (!empty($data)) {
      foreach ($data as $key => $value) {
        $paramUrl.= $key . '=' . $value.'&';
      }
      $url = $url .'&#63;'. $paramUrl;
    }
     
    //初始化類中的數(shù)據(jù)
    $this->url = $url;
     
    $this->data = $data;
    try{
      if(!$this->curl = curl_init()){
        throw new Exception('curl初始化錯(cuò)誤:');
      };
    }catch (Exception $e){
      echo '<pre class="brush:php;toolbar:false">';
      print_r($e->getMessage());
      echo '
'; } curl_setopt($this->curl, CURLOPT_URL, $this->url); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); } /** * [_post 設(shè)置get請(qǐng)求的參數(shù)] * @return [type] [description] */ public function _get() { } /** * [_post 設(shè)置post請(qǐng)求的參數(shù)] * post 新增資源 * @return [type] [description] */ public function _post() { curl_setopt($this->curl, CURLOPT_POST, 1); curl_setopt($this->curl, CURLOPT_POSTFIELDS, $this->data); } /** * [_put 設(shè)置put請(qǐng)求] * put 更新資源 * @return [type] [description] */ public function _put() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); } /** * [_delete 刪除資源] * delete 刪除資源 * @return [type] [description] */ public function _delete() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); } /** * [doRequest 執(zhí)行發(fā)送請(qǐng)求] * @return [type] [description] */ public function doRequest() { //發(fā)送給服務(wù)端驗(yàn)證信息 if((null !== self::token) && self::token){ $this->headers = array( 'Client_Token: '.self::token, 'Client_Code: '.$this->setAuthorization() ); } //發(fā)送頭部信息 $this->setHeader(); //發(fā)送請(qǐng)求方式 switch ($this->requestType) { case 'post': $this->_post(); break; case 'put': $this->_put(); break; case 'delete': $this->_delete(); break; default: curl_setopt($this->curl, CURLOPT_HTTPGET, TRUE); break; } //執(zhí)行curl請(qǐng)求 $info = curl_exec($this->curl); //獲取curl執(zhí)行狀態(tài)信息 $this->status = $this->getInfo(); return $info; } /** * 設(shè)置發(fā)送的頭部信息 */ private function setHeader(){ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); } /** * 生成授權(quán)碼 * @return string 授權(quán)碼 */ private function setAuthorization(){ $authorization = md5(substr(md5(self::token), 8, 24).self::token); return $authorization; } /** * 獲取curl中的狀態(tài)信息 */ public function getInfo(){ return curl_getinfo($this->curl); } /** * 關(guān)閉curl連接 */ public function __destruct(){ curl_close($this->curl); } }

testClient.php

<&#63;php
/**
 * Created by PhpStorm.
 * User: anziguoer@sina.com
 * Date: 2015/4/29
 * Time: 12:35
 */
 
include './ApiClient.php';
 
$arr = array(
  'user' => 'anziguoer',
  'passwd' => 'yangyulong'
);
// $url = 'http://localhost/restAPI/restServer.php';
$url = 'http://localhost/restAPI/testServer.php/user/123';
 
$rest = new restClient($url, $arr, 'get');
$info = $rest->doRequest();
 
//獲取curl中的狀態(tài)信息
$status = $rest->status;
echo '<pre class="brush:php;toolbar:false">';
print_r($info);
echo '
';

testServer.php

<&#63;php
/**
 * @Author: anziguoer@sina.com
 * @Email: anziguoer@sina.com
 * @link: https://git.oschina.net/anziguoer
 * @Date:  2015-04-30 16:52:53
 * @Last Modified by:  yangyulong
 * @Last Modified time: 2015-04-30 17:26:37
 */
 
include './ApiServer.php';
 
class testServer extends apiServer
{
  /**
   * 先執(zhí)行apiServer中的方法,初始化數(shù)據(jù)
   * @param object $obj 可以傳入的全局對(duì)象[數(shù)據(jù)庫對(duì)象,框架全局對(duì)象等]
   */
   
  private $obj;
 
  function __construct()//object $obj
  {
    parent::__construct();
    //$this->obj = $obj;
    //$this->resourse; 父類中已經(jīng)實(shí)現(xiàn),此類中可以直接使用
    //$tihs->resourseId; 父類中已經(jīng)實(shí)現(xiàn),此類中可以直接使用
  }
   
  /**
   * 獲取資源操作
   * @return [type] [description]
   */
  protected function _get(){
    echo "get";
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }  
 
  /**
   * 新增資源操作
   * @return [type] [description]
   */
  protected function _post(){
    echo "post";
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
 
  /**
   * 刪除資源操作
   * @return [type] [description]
   */
  protected function _delete(){
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
 
  /**
   * 更新資源操作
   * @return [type] [description]
   */
  protected function _put(){
    echo "put";
    //邏輯代碼根據(jù)自己實(shí)際項(xiàng)目需要實(shí)現(xiàn)
  }
}
 
$server = new testServer();

The above is the entire content of this article, I hope you all like it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/997902.htmlTechArticlephp makes a cross-platform restfule interface based on curl extension, phpcurlrestfule restfule interface applicable platform: cross-platform depends on: curl Extended git: https://git.oschina.net/anziguoer/re...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1502
276
PHP calls AI intelligent voice assistant PHP voice interaction system construction PHP calls AI intelligent voice assistant PHP voice interaction system construction Jul 25, 2025 pm 08:45 PM

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

How to use PHP to build social sharing functions PHP sharing interface integration practice How to use PHP to build social sharing functions PHP sharing interface integration practice Jul 25, 2025 pm 08:51 PM

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy PHP creates a blog comment system to monetize PHP comment review and anti-brush strategy Jul 25, 2025 pm 08:27 PM

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism PHP realizes commodity inventory management and monetization PHP inventory synchronization and alarm mechanism Jul 25, 2025 pm 08:30 PM

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution PHP integrated AI speech recognition and translator PHP meeting record automatic generation solution Jul 25, 2025 pm 07:06 PM

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.

See all articles