如果你现在正使用iphone、android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTful API。Representational state transfer (REST) 是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。
// If the method not exist with in this class, response would be "Page not found".
37
}
38
39
privatefunctionlogin()
40
{
41
..............
42
}
43
44
privatefunctionusers()
45
{
46
..............
47
}
48
49
privatefunctiondeleteUser()
50
{
51
.............
52
}
53
54
//Encode array into JSON
55
privatefunctionjson($data)
56
{
57
if(is_array($data)){
58
returnjson_encode($data);
59
}
60
}
61
}
62
63
// Initiiate Library
64
$api= newAPI;
65
$api->processApi();
提交登陆
通过访问REST API地址http://localhost/rest/login/ 显示从users表中查询出的用户数据。Restful API 的登录状态是根据状态码工作的。如果状态码为200,则登陆成功;否则状态码为204,会显示失败信息。更多的状态码信息请查看示例文件中的Rest.inc.php。
1
privatefunctionlogin()
2
{
3
// Cross validation if the request method is POST else it will return "Not Acceptable" status
4
if($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
13
if(!empty($email) and!empty($password))
14
{
15
if(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);
17
if(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/ 获取用户的信息。
1
privatefunctionusers()
2
{
3
// Cross validation if the request method is GET else it will return "Not Acceptable" status
4
if($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);
9
if(mysql_num_rows($sql) > 0)
10
{
11
$result= array();
12
while($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
如果你现在正使用iphone、android以及Web等多种平台工作,请看一下这篇文章,它会告诉你如何使用PHP创建RESTful API。Representational state transfer (REST) 是一个用于向不同应用分发数据的软件系统。Web服务系统会以JSON或者XML方式响应状态码。REST API处理流程数据库数据库表users包含了user_id,