YouTip LogoYouTip

Php Restful

-- Learn not just technology, but dreams! Home HTML JAVASCRIPT CSS VUE REACT PYTHON3 JAVA C C++ C# AI GO SQL LINUX VS CODE BOOTSTRAP GIT Local Bookmarks PHP Tutorial PHP Tutorial PHP Introduction PHP Installation PHP Syntax PHP Variables PHP echo/print PHP EOF(heredoc) PHP Data Types PHP Type Comparison PHP Constants PHP Strings PHP Operators PHP If...Else PHP Switch PHP Arrays PHP Array Sorting PHP Superglobals PHP While Loop PHP For Loop PHP Functions PHP Magic Constants PHP Namespaces PHP OOP PHP Quiz PHP Forms PHP Forms PHP Form Validation PHP Form - Required Fields PHP Form - Validate E-mail and URL PHP Complete Form Example PHP $_GET Variable PHP $_POST Variable PHP Advanced PHP Multidimensional Arrays PHP Date PHP Include PHP File PHP File Upload PHP Cookie PHP Session PHP E-mail PHP Secure E-mail PHP Error PHP Exception PHP Filters PHP Advanced Filters PHP JSON PHP 7 New Features PHP 7 New Features PHP Database PHP MySQL Introduction PHP MySQL Connection PHP MySQL Create Database PHP MySQL Create Table PHP MySQL Insert Data PHP MySQL Insert Multiple Records PHP MySQL Prepared Statements PHP MySQL Read Data PHP MySQL Where PHP MySQL Order By PHP MySQL Update PHP MySQL Delete PHP ODBC PHP XML XML Expat Parser XML DOM XML SimpleXML PHP and AJAX AJAX Introduction AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX RSS Reader AJAX Poll PHP Reference PHP Array PHP Calendar PHP cURL PHP Date PHP Directory PHP Error PHP Filesystem PHP Filter PHP FTP PHP HTTP PHP Libxml PHP Mail PHP Math PHP Misc PHP MySQLi PHP PDO PHP SimpleXML PHP String PHP XML PHP Zip PHP Timezones PHP Image Processing PHP RESTful PHP PCRE PHP Available Functions PHP Composer PHP Image Processing PHP Regular Expressions (PCRE) PHP RESTful REST (Representational State Transfer) refers to a set of architectural constraints and principles. A Web API that conforms to the REST design style is called a RESTful API. It is defined by the following three aspects of resources: Intuitive and concise resource address: URI, for example: http://example.com/resources/. Transmitted resources: Internet media types accepted and returned by the Web service, for example: JSON, XML, YAM, etc. Operations on resources: A series of request methods supported by the Web service on that resource (for example: POST, GET, PUT, or DELETE). In this tutorial, we will use PHP (without a framework) to create a RESTful web service. At the end of the article, you can download the code used in this chapter. Through this tutorial, you will learn the following: Create a RESTful Webservice. Use native PHP, without relying on any framework. URI patterns need to follow REST rules. The format accepted and returned by the RESTful service can be JSON, XML, etc. Respond with the corresponding HTTP status code according to different situations. Demonstrate the use of request headers. Use a REST client to test the RESTful web service. RESTful Webservice Example The following code is the RESTful service class Site.php: Example 'TaoBao', 2 => 'Google', 3 => '', 4 => 'Baidu', 5 => 'Weibo', 6 => 'Sina' ); public function getAllSite(){ return $this->sites; } public function getSite($id){ $site = array($id => ($this->sites[$id]) ? $this->sites[$id] : $this->sites); return $site; } } ?> RESTful Services URI Mapping RESTful Services URIs should be set to an intuitive and concise resource address. The Apache server's .htaccess should have the corresponding Rewrite rules set up. In this example, we will use two URI rules: 1. Get a list of all sites: http://localhost/restexample/site/list/ 2. Use an id to get a specific site, the following URI gets the site with id 3: http://localhost/restexample/site/list/3/ The .htaccess file configuration rules for the project are as follows: # Turn on rewrite engine Options +FollowSymlinks RewriteEngine on # Rewrite rules RewriteRule ^site/list/$ RestController.php?view=all [nc,qsa] RewriteRule ^site/list/(+)/$ RestController.php?view=single&id=$1 [nc,qsa] RESTful Web Service Controller In the .htaccess file, we set the parameter 'view' to get the corresponding request in the RestController.php file, and distribute it to different methods by getting different parameters of 'view'. The RestController.php file code is as follows: Example getAllSites(); break; case "single": // Handle REST Url /site/show// $siteRestHandler = new SiteRestHandler(); $siteRestHandler->getSite($_GET); break; case "" : //404 - not found; break; } ?> Simple RESTful Base Class The following provides a base class for RESTful, used to handle the HTTP status codes of response requests. The SimpleRest.php file code is as follows: Example getHttpStatusMessage($statusCode); header($this->httpVersion. " ". $statusCode ." ". $statusMessage); header("Content-Type:". $contentType); } public function getHttpStatusMessage($statusCode){ $httpStatus = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '(Unused)', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported'); return ($httpStatus[$statusCode]) ? $httpStatus[$statusCode] : $status; } } ?> RESTful Web Service Handler Class The following is a RESTful Web Service handler class SiteRestHandler.php, which inherits the RESTful base class we provided above. The class determines the returned HTTP status code and data format by judging the request parameters. In the example, we provide three data formats: "application/json", "application/xml", or "text/html": The SiteRestHandler.php file code is as follows: Example getAllSite(); if(empty($rawData)) { $statusCode = 404; $rawData = array('error' => 'No sites found!'); } else { $statusCode = 200; }
← C Header FilesC Preprocessors β†’