


PHP makes a cross-platform restfule interface based on curl extension_PHP tutorial
Jul 13, 2016 am 09:54 AMPHP makes a cross-platform restfule interface based on curl extension
This article mainly introduces the relevant information and detailed code of making a cross-platform restfule interface in PHP based on curl extension. There are Friends who need it can refer to it.
Restfule interface
Applicable platforms: cross-platform
Depends 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 43 44 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 84 85 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 119 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 180 181 182 183 184 185 186 |
/** * @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 { /** * Client request method * @var string */ private $method = '';
/** * Data sent by the client * @var [type] */ protected $param;
/** * The resource to be operated * @var [type] */ protected $resourse;
/** * Resource id to be operated * @var [type] */ protected $resourseId;
/** * Constructor, obtains the client request method and the transmitted data * @param object can customize the passed in object */ public function __construct() { //First verify the client’s request $this->authorization();
$this->method = strtolower($_SERVER['REQUEST_METHOD']);
//All requests are in pathinfo mode $pathinfo = $_SERVER['PATH_INFO'];
//Map pathinfo data information to the actual request method $this->getResourse($pathinfo);
//Get the specific parameters of transmission $this->getData();
//Execute response $this->doResponse(); }
/** * Obtain data according to different request methods * @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 /users: List all users page by page; * POST /users: Create a new user; * GET /users/123: Returns the detailed information of user 123; * PUT /users/123: Update user 123; * DELETE /users/123: Delete user 123; * * According to the above rules, map the first parameter of pathinfo to the data table that needs to be operated, * The second parameter is mapped to the id of the operation */
$info = explode('/', ltrim($pathinfo, '/')); list($this->resourse, $this->resourseId) = $info; }
/** * Verification request */ private function authorization(){ $token = $_SERVER['HTTP_CLIENT_TOKEN']; $authorization = md5(substr(md5($token), 8, 24).$token); if($authorization != $_SERVER['HTTP_CLIENT_CODE']){ //Verification fails and error message is output to the client $this->outPut($status = 1); } }
/** * [getData gets the transmitted parameter information] * @param [type] $pad [description] * @return [type] [description] */ private function getData(){ //All parameters are passed by get $this->param = $_GET; }
/** * Get resource operation * @return [type] [description] */ protected function _get(){ //The logic code is implemented according to your actual project needs }
/** * Add new resource operation * @return [type] [description] */ protected function _post(){ //The logic code is implemented according to your actual project needs }
/** * Delete resource operation * @return [type] [description] */ protected function _delete(){ //The logic code is implemented according to your actual project needs }
/** * Update resource operation * @return [type] [description] */ protected function _put(){ //The logic code is implemented according to your actual project needs }
/** * Data information returned by the server in json format */ public function outPut($stat, $data=array()){ $status = array( //0 status means the request is successful 0 => array( 'code' => 1, 'info' => 'Request successful', 'data' =>$data ), //Verification failed 1 => array( 'code' => 0, 'info' => 'Illegal request' ) );
try{ if(!in_array($stat, array_keys($status))){ throw new Exception('The entered status code is illegal'); }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 43 44 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 84 85 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 119 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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
? /** * 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 design guide] */ /*** * * * * * * * * * * * * * * * * * * * * * * * * * *** * Define the routing request method * * * * $url_model=0 * * Use traditional URL parameter mode * * http://serverName/appName/?m=module&a=action&id=1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * PATHINFO mode (default mode) * * Set url_model to 1 * * http://serverName/appName/module/action/id/1/ * ** * * * * * * * * * * * * * * * * * * * * * * * * * * ** */ class restClient { //Requested token const token='yangyulong';
//Request url private $url;
//Type of request private $requestType;
//Requested data private $data;
//curl instance private $curl;
public $status;
private $headers = array(); /** * [__construct construction method, initialization data] * @param [type] $url requested server address * @param [type] $requestType Method to send request * @param [type] $data The data sent * @param integer $url_model routing request method */ public function __construct($url, $data = array(), $requestType = 'get') {
//url must be passed, and it must be a path that conforms to the PATHINFO mode if (!$url) { return false; } $this->requestType = strtolower($requestType); $paramUrl = ''; //PATHINFO mode if (!empty($data)) { foreach ($data as $key => $value) { $paramUrl.= $key . '=' . $value.'&'; } $url = $url .'?'. $paramUrl; }
//Initialize the data in the class $this->url = $url;
$this->data = $data; try{ if(!$this->curl = curl_init()){ throw new Exception('curl initialization error: '); }; }catch (Exception $e){ echo ' ';</p> <p>print_r($e->getMessage());</p> <p>echo ''; }
curl_setopt($this->curl, CURLOPT_URL, $this->url); curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1);
}
/** * [_post sets the parameters of get request] * @return [type] [description] */ public function _get() {
}
/** * [_post sets the parameters of the post request] * post new resources * @return [type] [description] */ public function _post() {
curl_setopt($this->curl, 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_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'PUT'); }
/** * [_delete delete resource] * delete delete resource * @return [type] [description] */ public function _delete() { curl_setopt($this->curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
}
/** * [doRequest executes sending request] * @return [type] [description] */ public function doRequest() { //Send verification information to the server if((null !== self::token) && self::token){ $this->headers = array( 'Client_Token: '.self::token, 'Client_Code: '.$this->setAuthorization() ); }
//Send header information $this->setHeader();
//How to send a request 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);
//Get curl execution status information $this->status = $this->getInfo(); return $info; }
/** * Set the header information sent */ private function setHeader(){ curl_setopt($this->curl, CURLOPT_HTTPHEADER, $this->headers); }
/** * Generate authorization code * @return string authorization code */ private function setAuthorization(){ $authorization = md5(substr(md5(self::token), 8, 24).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
?
|
?>/**?>
?>* 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();
//Get status information in curl
$status = $rest->status;
echo ''; print_r($info); echo ''; testServer.php ?
The above is the entire content of this article, I hope you all like it. |

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

TovalidateuserinputinPHP,usebuilt-invalidationfunctionslikefilter_var()andfilter_input(),applyregularexpressionsforcustomformatssuchasusernamesorphonenumbers,checkdatatypesfornumericvalueslikeageorprice,setlengthlimitsandtrimwhitespacetopreventlayout

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

You can embed PHP code into HTML files, but make sure that the file has an extension of .php so that the server can parse it correctly. Use standard tags to wrap PHP code, insert dynamic content anywhere in HTML. In addition, you can switch PHP and HTML multiple times in the same file to realize dynamic functions such as conditional rendering. Be sure to pay attention to the server configuration and syntax correctness to avoid problems caused by short labels, quotation mark errors or omitted end labels.

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas
