PHP服务端开发APP接口

不言
Lepaskan: 2023-03-22 22:28:02
asal
8860 orang telah melayarinya

本篇文章介绍的是关于PHP服务端开发APP接口 ,现在给大家分享一下,有兴趣的朋友可以看一下


一、APP接口简介


什么是app接口?app接口就是用服务端程序如php写好的脚本,以供app客户端请求而获得数据的一个东西。比如一个商铺app的首页,肯定有一些商品列表,那么当你打开这个app时,这个封装在app里的这个首页其实会去请求一个远程php文件如:http://www.example.com/index.php 去获得需要展示在首页的商品列表数据。前端工程师拿到这些数据,就会按照特定的设计,将这些内容展示出来了。
接口要实现的目的就是这样。一个app内部通常需要访问多个php接口来获得不同的数据。下面具体讲一讲接口实现的流程以及实现接口需要的一些核心的技术。


二、PHP接口知识

JSON和XML方式封装通信接口

response.class.php

<?php/**
 *description 用于返回指定数据格式的类
 *@param $code [int] 返回的状态码
 *@param $message [string] 返回的状态信息
 *@param $data [array] 需要返回的数据
 *
 */class Response{
    public function json($code,$message,$data){
        $result = array(                "code" => $code,                "message" => $message,                "data" => $data
            );        return json_encode($result);
    }    public function xml($code,$message,$data){
        $result = array(                "code" => $code,                "message" => $message,                "data" => $data
            );
        header(&#39;Content-Type:text/xml&#39;);        $xml = "<?xml version=&#39;1.0&#39; encoding=&#39;UTF-8&#39;?>\n";        $xml .= "<root>";        $xml .= self::encodeXml($result);        $xml .= "</root>";        return $xml;
    }    /**
     *将数据解析为XML字符串
     */

    public static function encodeXml($data){
        $attr = $xml = "";        foreach($data as $key => $value){                if(is_numeric($key)){                    $attr = " id=&#39;{$key}&#39;";                    $key = "item";
                }                $xml .= "<{$key}{$attr}>";                $xml .= is_array($value)?self::encodeXml($value):$value;                $xml .= "</$key>";
        }        return $xml;
    }
}
Salin selepas log masuk

response.class.php是一个最简单的返回json或XML格式数据的类
下面贴出接口文件代码:
returndata.php

<?phprequire "response.class.php";    //引入返回信息类//准备返回数据$code = 200;$message = "信息请求成功";$data = array(        "name" => "ruanwnewu",        "sex"  => "1",        "age"  => "28",        "exp" => array(                "2012" => "北京瑞泰新",                "2013" => "兄弟连",                "2014" => "木蚂蚁科技"
            )
    );//实例化response类$response = new Response;//返回数据echo $response -> json($code,$message,$data);
Salin selepas log masuk

三、实际开发例子

  • 开发三个接口(登录、注册、文件上传),分别完成对应的功能

  • 因为本人不做APP开发,所以在实际的接口测试过程中,运用Firefox浏览器的RESTClient扩展模拟APP请求服务和接收数据
    (1)登录、注册接口的编写
    直接上代码:

<?phprequire ("../connect_db.php");$action = $_REQUEST["action"];$conn = db_connect();
mysql_query("set names &#39;utf8&#39;");
mysql_select_db("FECG");switch ($action){    case &#39;login&#39;:
       login();       break;    case &#39;register&#39;:
       register();       break;    case &#39;upload&#39;:
       upload();       break;    default:       break;
}//登录接口function login(){
    $account_name = $_POST["username"];    $password = $_POST["password"];    $result = mysql_query("SELECT * FROM app_account WHERE account_name=&#39;".$account_name."&#39;");    if (mysql_num_rows($result) > 0){        $row = mysql_fetch_array($result);        $salt = $row["salt"];        $new_password = md5($password."".$salt);        if ($new_password == $row["password"]){            //登录成功
            $current_time = new DateTime();            $login_time = $current_time -> format(&#39;Y-m-d H:i:s&#39;);            $result =  mysql_query("UPDATE app_account SET last_lgin_time=&#39;".$login_time."&#39; WHERE account_name=&#39;".$row[&#39;account_name&#39;]."&#39;");            $array = array();            $array["account_id"] = $row["account_id"];            $array["account_name"] = $row["account_name"];            $array["create_time"] = $row["creat_time"];            $json = json_encode(array(                  "resultCode"=>200,                  "message"=>"login successed!",                  "data"=>$array));            echo($json);
        }else{            $json = json_encode(array(                  "resultCode"=>500,                  "message"=>"The password is wrong!please try again."
                  ));            echo($json);
         }
    }else{        //登录失败
        $json = json_encode(array(              "resultCode"=>500,              "message"=>"please register!"
              ));        echo($json);
    }
}//注册接口function register(){
    $account_name = $_POST["username"];    $password = $_POST["password"];    $result = mysql_query("select * from app_account where account_name=&#39;".$account_name."&#39;");    //查询失败
    if (!$result){        $json = json_encode(array(              "resultCode"=>500,              "message"=>"select failed!"
              ));        echo($json);
    }    //用户名已经注册
    if (mysql_num_rows($result) > 0){        $json = json_encode(array(              "resultCode"=>500,              "message"=>"register failed!"
              ));        echo($json);
    }else{        //插入记录到数据库中
        $account_id = uniqid();        $salt = uniqid();        $new_password = md5($password."".$salt);        $current_time = new DateTime();        $create_time = $current_time -> format(&#39;Y-m-d H:i:s&#39;);        $last_login_time = $create_time;        $result = mysql_query("insert into app_account(account_id,account_name,password,salt,creat_time,last_lgin_time) values(&#39;".$account_id."&#39;, &#39;".$account_name."&#39;, &#39;".$new_password."&#39;, &#39;".$salt."&#39;, &#39;".$create_time."&#39;, &#39;".$last_login_time."&#39;)");        $user_id = uniqid();        $result1 = mysql_query("INSERT INTO app_user(user_id,username,account_id) VALUES(&#39;".$user_id."&#39;, &#39;".$account_name."&#39;, &#39;".$account_id."&#39;)");        if ($result){           $json = json_encode(array(                 "resultCode"=>200,                 "message"=>"register successed!"
                 ));           echo($json);
        }
    }
}//文件上传接口function upload(){}?>
Salin selepas log masuk

RESTClient测试:
这里写图片描述
(注册也是类似的操作)
(2)文件上传
因为是模拟,而文件上传接口涉及到文件的上传,RESTClient无法模拟。所以单独写一个客户端uploadClient.html来模拟文件上传。
uploadClient.html

<!DOCTYPE html><html><head>
    <title>文件上传</title>
    <meta charset="UTF-8" /></head><body><form action="upload.php" method="post" enctype="multipart/form-data" >
    选择文件:<input type="file" name="filename" />
    </br>
    用户ID:<input type="text" name="userid" /></br>
    心率:<input type="text" name="rate" /></br>
    <input type="submit" value="提交"></form></body></html>
Salin selepas log masuk

服务端接收文件接口upload.php
upload.php

<?phprequire ("../connect_db.php");$conn = db_connect();
mysql_query("set names &#39;utf8&#39;");
mysql_select_db("FECG");$file_name = $_POST["filename"];$userid = $_POST["userid"];$heart_rate = $_POST["rate"];if ($_FILES[&#39;filename&#39;][&#39;name&#39;] != NULL){    if ($_FILES[&#39;filename&#39;][&#39;error&#39;]){        $data = array(            "resultCode"=>1,            "message"=>"失败,上传文件出错!"
        );        echo json_encode($data);
    }    else{        //获取文件后缀名
        $file_extension = substr(strrchr($_FILES[&#39;filename&#39;][&#39;name&#39;], &#39;.&#39;), 1);        //判断文件夹是否存在
        $path = "/var/www/html/FECG/fecg_segment_data/".$userid;        if (!file_exists($path)){            //创建以用户名命名的文件夹
            if(mkdir ($path)){               $data = array("message"=>"ok");               echo json_encode($data);}
        }        //对上传文件进行命名
        $file_path = &#39;/var/www/html/FECG/fecg_segment_data/&#39;.$userid.&#39;/&#39;.date("YmdHis").".".$file_extension;        if (is_uploaded_file($_FILES[&#39;filename&#39;][&#39;tmp_name&#39;])){            $result = move_uploaded_file($_FILES[&#39;filename&#39;][&#39;tmp_name&#39;], $file_path);            if ($result){                //文件上传成功,进行第二步更新数据库
                $result = mysql_query("SELECT * FROM app_account WHERE account_name=&#39;".$userid."&#39;");                if (!$result){                     $num = 123;                     $data = array(                        "resultCode"=>2,                        "message"=>"userid",                        "data"=>$userid
                     );                     echo json_encode($data);
                }                $row = mysql_fetch_array($result, MYSQL_ASSOC);                $account_id = $row["account_id"];                $result1 = mysql_query("SELECT * FROM app_user WHERE account_id=&#39;".$account_id."&#39;");                $row1 = mysql_fetch_array($result1, MYSQL_ASSOC);                $user_id = $row1["user_id"];                $user_name = $row1["username"];                $ecg_segment_id = uniqid();                $channel = 3;                $current_time = new DateTime();                $create_time = $current_time -> format(&#39;Y-m-d H:i:s&#39;);                $result = mysql_query("INSERT INTO ecg_segment(ecg_segment_id,channel,heart_rate,ecg_url,user_name,user_id)
                                      VALUES(&#39;".$ecg_segment_id."&#39;, &#39;".$channel."&#39;, &#39;".$heart_rate."&#39;, &#39;".$file_path."&#39;, &#39;".$user_name."&#39;, &#39;".$user_id."&#39;)");                $task_id = uniqid();                $server_analysis = "异常";                $result1 = mysql_query("INSERT INTO task(task_id,creat_time,server_analysis,ecg_segment_id)
                                      VALUES(&#39;".$task_id."&#39;, &#39;".$create_time."&#39;, &#39;".$server_analysis."&#39;, &#39;".$ecg_segment_id."&#39;)");                if ($result){                    $data = array(                        "resultCode"=>2,                        "message"=>"文件上传成功!"
                        );                    echo json_encode($data);
                }                else{                    $data = array(                        "resultCode"=>3,                        "message"=>"服务器错误!"
                        );                    echo json_encode($data);
                }
            }            else{                $data = array(                    "resultCode"=>4,                    "message"=>"uploaded failed!"
                    );                echo json_encode($data);
            }
        }        else{            $data = array(                "resultCode"=>5,                "message"=>"文件上传失败!"
            );            echo json_encode($data);
        }
    }
}else{    $data = array(         "resultCode"=>300,         "message"=>"文件名不能为空!"
         );    echo json_encode($data);
}?>
Salin selepas log masuk

(上述代码都是根据本人项目需要开发的相应接口)

相关推荐:

最清晰的PHP服务端环境搭建的图文教程

七牛云存储 - PILI直播 PHP服务端SDK 代码怎么引入到自己的项目中?

移动端与PHP服务端接口通信流程设计增强版


Atas ialah kandungan terperinci PHP服务端开发APP接口. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!