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

Home Backend Development PHP Tutorial PHP creates a cross-platform restfule interface based on curl extension

PHP creates a cross-platform restfule interface based on curl extension

Jan 05, 2017 pm 02:07 PM

restfule interface
Applicable platforms: cross-platform
Depends on: curl extension
git: https://git.oschina.net/anzigu

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

ApiServer.php

<?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 = &#39;&#39;;
  
  /**
   * 客戶端發(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[&#39;REQUEST_METHOD&#39;]);
  
    //所有的請(qǐng)求都是pathinfo模式
    $pathinfo = $_SERVER[&#39;PATH_INFO&#39;];
  
    //將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 &#39;get&#39;:
        $this->_get();
        break;
      case &#39;post&#39;:
        $this->_post();
        break;
      case &#39;delete&#39;:
        $this->_delete();
        break;
      case &#39;put&#39;:
        $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(&#39;/&#39;, ltrim($pathinfo, &#39;/&#39;));
    list($this->resourse, $this->resourseId) = $info;
  }
  
  /**
   * 驗(yàn)證請(qǐng)求
   */
  private function authorization(){
    $token = $_SERVER[&#39;HTTP_CLIENT_TOKEN&#39;];
    $authorization = md5(substr(md5($token), 8, 24).$token);
    if($authorization != $_SERVER[&#39;HTTP_CLIENT_CODE&#39;]){
      //驗(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(
        &#39;code&#39; => 1,
        &#39;info&#39; => &#39;請(qǐng)求成功&#39;,
        &#39;data&#39; =>$data
      ),
      //驗(yàn)證失敗
      1 => array(
        &#39;code&#39; => 0,
        &#39;info&#39; => &#39;請(qǐng)求不合法&#39;
      )
    );
  
    try{
      if(!in_array($stat, array_keys($status))){
        throw new Exception(&#39;輸入的狀態(tài)碼不合法&#39;);
      }else{
        echo json_encode($status[$stat]);
      }
    }catch (Exception $e){
      die($e->getMessage());
    }
  }
}

ApiClient.php

<?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/?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=&#39;yangyulong&#39;;
  
  //請(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 = &#39;get&#39;) {
      
    //url是必須要傳的,并且是符合PATHINFO模式的路徑
    if (!$url) {
      return false;
    }
    $this->requestType = strtolower($requestType);
    $paramUrl = &#39;&#39;;
    // PATHINFO模式
    if (!empty($data)) {
      foreach ($data as $key => $value) {
        $paramUrl.= $key . &#39;=&#39; . $value.&#39;&&#39;;
      }
      $url = $url .&#39;?&#39;. $paramUrl;
    }
      
    //初始化類中的數(shù)據(jù)
    $this->url = $url;
      
    $this->data = $data;
    try{
      if(!$this->curl = curl_init()){
        throw new Exception(&#39;curl初始化錯(cuò)誤:&#39;);
      };
    }catch (Exception $e){
      echo &#39;<pre class="brush:php;toolbar:false">&#39;;
      print_r($e->getMessage());
      echo &#39;
'; } 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

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

testServer.php

<?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 &#39;./ApiServer.php&#39;;
  
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.

For more PHP-based curl extensions to create cross-platform restfule interface related articles, please pay attention to the PHP Chinese website!

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 Variable Scope Explained PHP Variable Scope Explained Jul 17, 2025 am 04:16 AM

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

Commenting Out Code in PHP Commenting Out Code in PHP Jul 18, 2025 am 04:57 AM

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

Tips for Writing PHP Comments Tips for Writing PHP Comments Jul 18, 2025 am 04:51 AM

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

Learning PHP: A Beginner's Guide Learning PHP: A Beginner's Guide Jul 18, 2025 am 04:54 AM

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

How to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

Quick PHP Installation Tutorial Quick PHP Installation Tutorial Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

See all articles