PHP based on Curl extension to make Cross-platform Restfule interface

Source: Internet
Author: User
Tags constructor curl getmessage md5 resource

This article mainly introduces the PHP based on Curl extension to make Cross-platform Restfule interface information and detailed code, the need for small partners can refer to.

Restfule interface

Platform for application: Cross-platform

Dependent on: Curl extension

Git:https://git.oschina.net/anziguoer/restapi

apiserver.php

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 186 <?php/** * @Author: Yangyulong * @Email: anziguoer@sina.com * @Date: 2015-04-30 05:38:34 * @Last Modified By:yangyu Long * @Last Modified time:2015-04-30 17:14:11/  class Apiserver {/** * client request * @var string/private $metho d = ';  /** * The data sent by the client * @var [type]/protected $param;  /** * The resources to be operated * @var [type] * */protected $resourse;  /** * The resource ID to be manipulated * @var [type] */protected $resourseId;    /** * constructor, get the way of the client request, and transmit data * @param object can customize the incoming object/Public function __construct () {//First request to the client Verify the $this->authorization ();   $this->method = strtolower ($_server[' Request_method '));  //All requests are pathinfo mode $pathinfo = $_server[' path_info '];  //mapping PathInfo data to the actual request method $this->getresourse ($pathinfo);  //Get the specific parameters of the transmission $this->getdata ();  //Execution Response $this->doresponse (); }  /** * According to different request method, obtain data * @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 }  //Map PathInfo data information to the actual request method Private function Getresourse ($pathinfo) { /** * Map PathInfo data information to the actual request method * get/u Sers: List all users by page; * Post/users: Create a new user; * get/users/123: Returns the user 123 details; * put/users/123: Update user 123; * delete/users/123: Delete user 123; * * According to the above rules, the first parameter of PathInfo is mapped to the data table that needs to be manipulated, * The second parameter is mapped to the Operation ID * *   $info = explode ('/', LTrim ($pathinfo, '/')); List ($this->resourse, $this->resourseid) = $info; }  /** * Authentication request/Private Function authorization () {$token = $_server[' Http_client_token ']; $authorization = MD5 (Subs TR (MD5 ($token), 8). $token); if ($authorization!= $_server[' Http_client_code ']) {//validation fails, output error message to client $this->output ($status = 1);}  /** * [getData fetch parameter information] * @param [Type] $pad [description] * @return [type] [description]/Private function get Data () {//All parameters are get pass $this->param = $_get;}  /** * Get Resource operations * @return [type] [description]/protected function _get () {//logical code to implement in accordance with its actual project}  /** * New Resources exercise * @return [Type] [description]/protected function _post () {//logical code to be implemented according to its actual project}  /** * Delete resource operation * @return [type] [Description]/protected function _delete () {//logical code to be implemented according to its actual project}  /** * Update Resource operations * @return [type] [description] * * protected function _put () {//logical code according to its own actual project needs to implement}  /** * Access to the data information returned by the server JSON format */Public Function OutPut ($stat, $data =ar Ray ()) {$status = array (//0 status indicates successful request 0 => array (' Code ' => 1, ' info ' => ' request succeeded ', ' data ' => $data),//validation failed 1 =& Gt Array (' code ' => 0, ' info ' => ' request illegal '));   try{if (!in_array ($stat, Array_keys ($status)) {throw new Exception (' Input status code not valid ');} else{Echo Json_encode ($status [$stat]);} catch (Exception $e) {die ($e->getmessage ());} }

apiclient.php

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26-27--28 29---30 31--32 33 34 35 36 37 38-39 40 41 42 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 5, 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 11 9 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148-149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179-18 0 181 182 183 184 185 186 187 188 189 190 191 192 193-194 195 <?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.htm l [RESTful Design Guide] * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * http://serverName/appName/?m=module&a=action&id=1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * pathinfo mode (default mode) * Set Url_model 1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * token token= ' restclient '///Request URL private $url &N Bsp Type of request private $requestType;  //Request data private $data;  //curl instance private $curl;   Public $status;   Private $headers = Array (); /** * [__construct constructor, initialization data] * @param [type] $url requested server address * @param [type] $requestType the method of sending the request * @param [type] $data Sent data * @param integer $url _model routing Request/Public function __construct ($url, $data = Array (), $requestType = ' get ') { //url is required to be passed, and is a path that conforms to PathInfo mode if (! $url) {return false;} $this-&G T;requesttype = Strtolower ($requestType); $PARAMURL = '; PathInfo mode if (!empty ($data)) {foreach ($data as $key => $value) {$paramUrl. = $key. '=' . $value. ' & '; $url = $url. '? '. $PARAMURL;  //initialization data in class $this->url = $url;   $this->data = $data; try{if (! $this->curl = Curl_init ()) {throw new Exception (' Curl initialization error: ');} catch (Exception $e) {echo ' <pre> '; Print_r ($e->getmessage ()); Echo ' </pre> ';}   curl_setopt ($this- >curl, Curlopt_url, $this->url); curl_setopt ($this->curl, Curlopt_returntransfer, 1);  }  /** * [_post Set the parameters of Get request] * @return [type] [description]/Public function _get () { }  /** * [_post set parameters for POST request] * Post New resource * @return [type] [description]/Public function _post () {  curl_setopt ($this->c URL, curlopt_post, 1);   curl_setopt ($this->curl, CurloPt_postfields, $this->data);  }  /** * [_put set put request] * put update resource * @return [type] [description]/Public function _put () {  Curl_set Opt ($this->curl, curlopt_customrequest, ' put '); }  /** * [_delete Delete Resource] * Delete resource * @return [type] [description]/Public Function _delete () {curl_setopt ($thi S->curl, Curlopt_customrequest, ' DELETE ');  }  /** * [dorequest Execute send request] * @return [type] [description]/Public function dorequest () {//Sent to server-side validation information if ( Null!== self::token) && self::token) {$this->headers = array (' Client_token: '. Self::token, ' Client_code: '. $ This->setauthorization ());  //Send header information $this->setheader ();  //Send request mode 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 //Execute Curl Request $info = curl_exec ($this->curl);  Gets the Curl execution state information $this->status = $this->getinfo (); return $info;  /** * Set header information sent/private function SetHeader () {curl_setopt ($this->curl, Curlopt_httpheader, $this->heade RS); }  /** * Generate Authorization Code * @return String Authorization code */Private Function setauthorization () {$authorization = MD5 (substr MD5 (self::to Ken), 8, Self::token); return $authorization; /** * Get status information in Curl/Public function getInfo () {return curl_getinfo ($this->curl);}  /** * Close Curl Connection/public function __destruct () {curl_close ($this->curl);}

testclient.php

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24-25 <?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 (); Gets the status information in the curl $status = $rest->status; Echo ' <pre> '; Print_r ($info); Echo ' </pre> ';

testserver.php

?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 The <?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 modif IED time:2015-04-30 17:26:37 */  include './apiserver.php ';   Class TestServer extends Apiserver {/** * First executes the method in Apiserver, initializing data * @param object $obj Global objects that can be passed in [Database objects, framework global objects, etc.] * *   Private $obj;   function __construct ()//object $obj {parent::__construct ();//$this->obj = $obj;//$this->resourse; is already implemented in the parent class and can be used directly in this class//$TIHS->resourseid; Implemented in the parent class, which can be used directly with the}  /** * To obtain resource operations * @return [type] [description]/protected function _get () {echo "get";//Logical code based on self Actual project needs to implement}  /** * New Resource Operations * @return [type] [description]/protected function _post () {echo "POST";//Logical code implemented according to its actual project}  /** * Delete Resource for * @return [type] [description]/protected function _delete () {//logical code to implement in accordance with its actual project}  /** * Update Resource operations * @return [type ] [description]/protected function _put () {echo "put";//Logical code is implemented according to its actual project}   $server = new TestServer ();

The above is the entire contents of this article, I hope you can enjoy.

Related Article

Cloud Intelligence Leading the Digital Future

Alibaba Cloud ACtivate Online Conference, Nov. 20th & 21st, 2019 (UTC+08)

Register Now >

Starter Package

SSD Cloud server and data transfer for only $2.50 a month

Get Started >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.