想要自己一个人完成app,那么后台接口也必须自己动动手。不用担心,其实很简单的,给自己信心!
下面就以登录注册为例,做一个api接口

首先在mac上搭建PHP环境,下载 MAMP Pro for Mac 3.4 破解版:

http://www.ifunmac.com/2015/08/mamp-pro-3-4/
即可一键安装Apache/PHP/MySQL开发环境。简单吧。

有了环境就可以写代码了:

首先写一个Config.php (配置数据库)

1 <?php
2
3 //定义数据库连接所需的变量
4 define("DB_HOST", "localhost");
5 define("DB_USER", "root");
6 define("DB_PASSWORD", "master12!");
7 define("DB_DATABASE", "loginAPI");
8
9 ?>

写一个DB_Connect.php(用于连接数据库)

 1 <?php
2
3 class DB_Connect
4 {
5 public $con;
6
8 function __construct()
9 {
10
11 }
12
14 function __destruct()
15 {
16 // $this->close();
17 }
18
19 //连接数据库
20 public function connect()
21 {
22 require_once 'include/Config.php';
23 //连接mysql
24 $this->con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error($this->con));
25 if (mysqli_connect_errno()) {
26 die("Database connection failed");
27 }
28
29 // 返回 database handler
30 return $this->con;
31 }
32
33 //关闭数据连接
34 public function close()
35 {
36 mysqli_close($this->con);
37 }
38
39 }
40
41 ?>

再来一个:DB_Functions.php (用来封装 执行sql后 返回数据的方法)

  1 <?php
2
3 class DB_Functions {
4
5 private $db;
6
7 // constructor
8 function __construct() {
9 require_once 'DB_Connect.php';
10 // connecting to database
11 $this->db = new DB_Connect();
12 $this->db->connect();
13 }
14
15 // destructor
16 function __destruct() {
17
18 }
19
20 /**
21 * 添加用户信息
22 */
23 public function storeUser($name, $email, $password) {
24 $uuid = uniqid('', true);
25 $hash = $this->hashSSHA($password);
26 $encrypted_password = $hash["encrypted"]; // 加密后的密文
27 $salt = $hash["salt"]; // salt
28 $result = mysqli_query($this->db->con,"INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
29 // 检查结果
30 if ($result) {
31 // 获取用户信息
32 $uid = mysqli_insert_id($this->db->con); // 获取最新的id
33 $result = mysqli_query($this->db->con,"SELECT * FROM users WHERE uid = $uid");
34 //返回刚插入的用户信息
35 return mysqli_fetch_array($result);
36 } else {
37 return false;
38 }
39 }
40
41 /**
42 * 通过email和password获取用户信息
43 */
44 public function getUserByEmailAndPassword($email, $password) {
45 $result = mysqli_query($this->db->con,"SELECT * FROM users WHERE email = '$email'") or die(mysqli_connect_errno());
46 // check for result
47 $no_of_rows = mysqli_num_rows($result);
48 if ($no_of_rows > 0) {
49 $result = mysqli_fetch_array($result);
50 $salt = $result['salt'];
51 $encrypted_password = $result['encrypted_password'];
52 $hash = $this->checkhashSSHA($salt, $password);
53 // check for password
54 if ($encrypted_password == $hash) {
55 return $result;
56 }
57 } else {
58 return false;
59 }
60 }
61
62 /**
63 * 通过email判断用户是否存在
64 */
65 public function isUserExisted($email) {
66 $result = mysqli_query($this->db->con,"SELECT email from users WHERE email = '$email'");
67 $no_of_rows = mysqli_num_rows($result);
68 if ($no_of_rows > 0) {
69 // 用户存在
70 return true;
71 } else {
72 //用户不存在
73 return false;
74 }
75 }
76
77 /**
78 * 加密
79 * @param password
80 * returns salt and encrypted password
81 */
82 public function hashSSHA($password) {
83
84 $salt = sha1(rand());
85 $salt = substr($salt, 0, 10);
86 $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
87 $hash = array("salt" => $salt, "encrypted" => $encrypted);
88 return $hash;
89 }
90
91 /**
92 * 解密
93 * @param salt, password
94 * returns hash string
95 */
96 public function checkhashSSHA($salt, $password) {
97
98 $hash = base64_encode(sha1($password . $salt, true) . $salt);
99
100 return $hash;
101 }
102
103 }
104
105 ?>

在Index.php调用并输出返回值(这个文件地址就是接口的访问地址)

 1 <?php
2
3 if (isset($_POST['tag']) && $_POST['tag'] != '') {
4 // tag是接口请求时post的值(方法名称),用来区别调用方法
5 $tag = $_POST['tag'];
6
7 //引用DB_Functions.php
8 require_once 'include/DB_Functions.php';
9 $db = new DB_Functions();
10
11 // 定义输入数组
12 $response = array("tag" => $tag, "error" => FALSE);
13
14 // 判断tag值
15 if ($tag == 'login') {
16 //获取login方法的post参数
17 $email = $_POST['email'];
18 $password = $_POST['password'];
19
20 // 通过email 和password获取用户信息
21 $user = $db->getUserByEmailAndPassword($email, $password);
22 if ($user != false) {
23 //找到用户信息
24 $response["error"] = FALSE;
25 $response["uid"] = $user["unique_id"];
26 $response["user"]["name"] = $user["name"];
27 $response["user"]["email"] = $user["email"];
28 $response["user"]["created_at"] = $user["created_at"];
29 $response["user"]["updated_at"] = $user["updated_at"];
30 echo json_encode($response);
31 } else {
32 //没有找到用户信息
33 //输出错误信息
34 $response["error"] = TRUE;
35 $response["error_msg"] = "帐号或密码不正确!";
36 echo json_encode($response);
37 }
38 } else if ($tag == 'register') {
39 //注册帐号
40 $name = $_POST['name'];
41 $email = $_POST['email'];
42 $password = $_POST['password'];
43
44 // 判断用户是否存在
45 if ($db->isUserExisted($email)) {
46 // 如果用户存在就返错误提示
47 $response["error"] = TRUE;
48 $response["error_msg"] = "用户已存在";
49 echo json_encode($response);
50 } else {
51 // 新增用户
52 $user = $db->storeUser($name, $email, $password);
53 if ($user) {
54 //新增成功返回用户信息
55 $response["error"] = FALSE;
56 $response["uid"] = $user["unique_id"];
57 $response["user"]["name"] = $user["name"];
58 $response["user"]["email"] = $user["email"];
59 $response["user"]["created_at"] = $user["created_at"];
60 $response["user"]["updated_at"] = $user["updated_at"];
61 echo json_encode($response);
62 } else {
63 // 新增失败,返回错误信息
64 $response["error"] = TRUE;
65 $response["error_msg"] = "服务器繁忙,操作失败";
66 echo json_encode($response);
67 }
68 }
69 } else {
70 // tag值无效时
71 $response["error"] = TRUE;
72 $response["error_msg"] = "未找到您要的方法";
73 echo json_encode($response);
74 }
75 } else {
76 $response["error"] = TRUE;
77 $response["error_msg"] = "您的参数不正确!";
78 echo json_encode($response);
79 }
80 ?>

转自:http://www.cnblogs.com/kissdodog/p/4159176.html

http://www.cnblogs.com/kissdodog/p/4159176.html的更多相关文章

  1. javascript Windouw 转自 http://www.cnblogs.com/kissdodog/archive/2013/01/01/2841464.html

    javascript之window对象 window :window对象是BOM中所有对象的核心,除了是BOM中所有对象的父对象外,还包含一些窗口控制函数. 1.全局的window对象 JavaScr ...

  2. Mysql----索引原理与慢查询优化

    一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,在生产环境中,我们遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,因此对查询语句 ...

  3. mysql六:索引原理与慢查询优化

    一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,在生产环境中,我们遇到最多的,也是最容易出问题的,还是一些复杂的查询操作,因此对查询语句 ...

  4. 初谈SQL Server逻辑读、物理读、预读

    前言 本文涉及的内容均不是原创,是记录自己在学习IO.执行计划的过程中学习其他大牛的博客和心得并记录下来,之所以想写下来是为了记录自己在追溯的过程遇到的几个问题,并把这些问题弄清楚. 本章最后已贴出原 ...

  5. ajaxFileUpload插件

    关键词: $.ajaxFileUpLoad(); data status dataType 参考资料: http://www.cnblogs.com/kissdodog/archive/2012/12 ...

  6. 【转】MySql中的函数

    原文:http://www.cnblogs.com/kissdodog/p/4168721.html MySQL数据库提供了很多函数包括: 数学函数: 字符串函数: 日期和时间函数: 条件判断函数: ...

  7. Comet技术

    1.Comet是什么? 维基百科: Comet是一种用于web的推送技术,能使服务器实时地将更新的信息传送到客户端,而无须客户端发出请求,目前有两种实现方式,长轮询和iframe流. 说白了就是web ...

  8. Xml序列化去掉命名空间,去掉申明

    #region 序列化        /// <summary>        /// 序列化        /// </summary>        /// <par ...

  9. .net学习笔记----HttpRequest,WebRequest,HttpWebRequest区别

    WebRequest是一个虚类/基类,HttpWebRequest是WebRequest的具体实现 HttpRequest类的对象用于服务器端,获取客户端传来的请求的信息,包括HTTP报文传送过来的所 ...

随机推荐

  1. android okvolley框架搭建

    最近新出了很多好东西都没时间去好好看看,现在得好好复习下了,记下笔记 记得以前用的框架是android-async-http,volley啊,或者其它的,然后后面接着又出了okhttp,retrofi ...

  2. 【转】你所不知道的HTML <head/> 头标签

    HTML的头部内容特别多,有针对SEO的头部信息,也有针对移动设备的头部信息.而且各个浏览器内核以及各个国内浏览器厂商都有些自己的标签元素,有很多差异性.移动端的工作已经越来越成为前端工作的重要内容, ...

  3. RHEL6和RHEL7恢复root用户密码

    一.RHEL6恢复root密码 将系统重启,出现如下界面按上下键选择会停住,并输入e键 选中下图红框选项,再输入e键 再输入1,进入单用户模式 输入b进行启动   修改密码,然后重启 二.RHEL7恢 ...

  4. 异步HTTPHandler的实现

    使用APM的方式实现 using System; using System.Web; using System.Threading; class HelloWorldAsyncHandler : IH ...

  5. [转]Web APi之认证(Authentication)及授权(Authorization)【一】(十二)

    本文转自:http://www.cnblogs.com/CreateMyself/p/4856133.html 前言 无论是ASP.NET MVC还是Web API框架,在从请求到响应这一过程中对于请 ...

  6. Leetcode, construct binary tree from inorder and post order traversal

    Sept. 13, 2015 Spent more than a few hours to work on the leetcode problem, and my favorite blogs ab ...

  7. struts2中各个jar包作用

    Struts2.3.4 所需的Jar包及介绍 Jar包的分类 jar包名称 jar包版本 jar包 文件名 jar包 的作用 jar包内包含的主要包路径及主要类 依赖的自有jar包名称 依赖的第三方j ...

  8. 神奇的BFC以及被忽略的东西

    BFC是CSS中一个非常重要的概念,经常用来清除浮动以及处理外边距折叠,但BFC到底是个什么东西却很难准确的表达清楚,国内的相关技术文档基本都不全面,本文的目的就是对BFC的方方面面做个整理,当然未必 ...

  9. C语言学习 第七次作业总结

    C语言学习 第七次作业总结 数组可以分为数组和多下标数组(在传统的国内C语言书本中,将其称为二/多维数组). 数组名称 在之前的课程中,大家应该都有印象,对于int a这样的定义,会为变量 a 声明一 ...

  10. 反序列化漏洞问题研究之php篇

    php的反序列化反序列化漏洞又称php对象注入(php Object Injection)产生的问题主要分以下两类: 将传来的序列化数据直接unserilize,造成魔幻函数的执行.这种情况在一般的应 ...