PHP教程:REST API示例

如果你现在正使用iphone、android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTful API。Representational state transfer (REST) 是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。

REST API处理流程

REST API处理流程

数据库

数据库表users包含了user_id, user_fullname, user_email, user_password 和 user_status字段,十分简单。

1CREATE TABLE IF NOT EXISTS `users`
2(
3`user_id` int(11) NOT NULL AUTO_INCREMENT,
4`user_fullname` varchar(25) NOT NULL,
5`user_email` varchar(50) NOT NULL,
6`user_password` varchar(50) NOT NULL,
7`user_status` tinyint(1) NOT NULL DEFAULT '0',
8PRIMARY KEY (`user_id`)
9) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Rest API类:api.php

代码十分简单,你需要修改数据库配置信息,如数据库名、数据库账户以及密码。

1require_once("Rest.inc.php");
2 
3class API extends REST
4{
5public $data = "";
6const DB_SERVER = "localhost";
7const DB_USER = "Database_Username";
8const DB_PASSWORD = "Database_Password";
9const DB = "Database_Name";
10 
11private $db = NULL;
12 
13public function __construct()
14{
15parent::__construct();// Init parent contructor
16$this->dbConnect();// Initiate Database connection
17}
18 
19//Database connection
20private function dbConnect()
21{
22$this->db = mysql_connect(self::DB_SERVER,self::DB_USER,self::DB_PASSWORD);
23if($this->db)
24mysql_select_db(self::DB,$this->db);
25}
26 
27//Public method for access api.
28//This method dynmically call the method based on the query string
29public function processApi()
30{
31$func = strtolower(trim(str_replace("/","",$_REQUEST['rquest'])));
32if((int)method_exists($this,$func) > 0)
33$this->$func();
34else
35$this->response('',404);
36// If the method not exist with in this class, response would be "Page not found".
37}
38 
39private function login()
40{
41..............
42}
43 
44private function users()
45{
46..............
47}
48 
49private function deleteUser()
50{
51.............
52}
53 
54//Encode array into JSON
55private function json($data)
56{
57if(is_array($data)){
58return json_encode($data);
59}
60}
61}
62 
63// Initiiate Library
64$api = new API;
65$api->processApi();

提交登陆

通过访问REST API地址http://localhost/rest/login/ 显示从users表中查询出的用户数据。Restful API 的登录状态是根据状态码工作的。如果状态码为200,则登陆成功;否则状态码为204,会显示失败信息。更多的状态码信息请查看示例文件中的Rest.inc.php。

1private function login()
2{
3// Cross validation if the request method is POST else it will return "Not Acceptable" status
4if($this->get_request_method() != "POST")
5{
6$this->response('',406);
7}
8 
9$email = $this->_request['email'];
10$password = $this->_request['pwd'];
11 
12// Input validations
13if(!empty($email) and !empty($password))
14{
15if(filter_var($email, FILTER_VALIDATE_EMAIL)){
16$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_email = '$email' AND user_password = '".md5($password)."' LIMIT 1", $this->db);
17if(mysql_num_rows($sql) > 0){
18$result = mysql_fetch_array($sql,MYSQL_ASSOC);
19 
20// If success everythig is good send header as "OK" and user details
21$this->response($this->json($result), 200);
22}
23$this->response('', 204); // If no records "No Content" status
24}
25}
26 
27// If invalid inputs "Bad Request" status message and reason
28$error = array('status' => "Failed", "msg" => "Invalid Email address or Password");
29$this->response($this->json($error), 400);
30}

获取用户信息

通过访问REST API 地址http://localhost/rest/users/ 获取用户的信息。

1private function users()
2{
3// Cross validation if the request method is GET else it will return "Not Acceptable" status
4if($this->get_request_method() != "GET")
5{
6$this->response('',406);
7}
8$sql = mysql_query("SELECT user_id, user_fullname, user_email FROM users WHERE user_status = 1", $this->db);
9if(mysql_num_rows($sql) > 0)
10{
11$result = array();
12while($rlt = mysql_fetch_array($sql,MYSQL_ASSOC))
13{
14$result[] = $rlt;
15}
16// If success everythig is good send header as "OK" and return list of users in JSON format
17$this->response($this->json($result), 200);
18}
19$this->response('',204); // If no records "No Content" status
20}

删除用户信息

根据user_id删除特定用户的信息,只需要访问REST API地址http://localhost/rest/deleteUser/

1private function deleteUser()
2{
3 
4if($this->get_request_method() != "DELETE"){
5$this->response('',406);
6}
7$id = (int)$this->_request['id'];
8if($id > 0)
9{
10mysql_query("DELETE FROM users WHERE user_id = $id");
11$success = array('status' => "Success", "msg" => "Successfully one record deleted.");
12$this->response($this->json($success),200);
13}
14else
15{
16$this->response('',204); // If no records "No Content" status
17}
18}

Chrome拓展

测试PHP restful API 响应的一个chrome的插件为Advanced REST client Application

.htaccess code
使用.htaccess使URL更加友好。在demo示例中修改htaccess.txt to .htaccess。

1<IfModule mod_rewrite.c>
2RewriteEngine On
3RewriteCond %{REQUEST_FILENAME} !-d
4RewriteCond %{REQUEST_FILENAME} !-s
5RewriteRule ^(.*)$ api.php?rquest=$1 [QSA,NC,L]
6 
7RewriteCond %{REQUEST_FILENAME} -d
8RewriteRule ^(.*)$ api.php [QSA,NC,L]
9 
10RewriteCond %{REQUEST_FILENAME} -s
11RewriteRule ^(.*)$ api.php [QSA,NC,L]
12</IfModule>

Demo示例下载:

PHP示例源码:REST API示例PHP示例源码:REST API示例(104)

原文出自:http://www.9lessons.info/2012/05/create-restful-services-api-in-php.html

本文由PHP爱好者原创翻译!转载请注明链接!


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值