本篇文章介紹的是關於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('Content-Type:text/xml'); $xml = "<?xml version='1.0' encoding='UTF-8'?>\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='{$key}'"; $key = "item"; } $xml .= "<{$key}{$attr}>"; $xml .= is_array($value)?self::encodeXml($value):$value; $xml .= "</$key>"; } return $xml; }}
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);
三、實際開發例子
<?phprequire ("../connect_db.php");$action = $_REQUEST["action"];$conn = db_connect();mysql_query("set names 'utf8'");mysql_select_db("FECG");switch ($action){ case 'login': login(); break; case 'register': register(); break; case 'upload': upload(); break; default: break;}//登入介面function login(){ $account_name = $_POST["username"]; $password = $_POST["password"]; $result = mysql_query("SELECT * FROM app_account WHERE account_name='".$account_name."'"); 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('Y-m-d H:i:s'); $result = mysql_query("UPDATE app_account SET last_lgin_time='".$login_time."' WHERE account_name='".$row['account_name']."'"); $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='".$account_name."'"); //查詢失敗 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('Y-m-d H:i:s'); $last_login_time = $create_time; $result = mysql_query("insert into app_account(account_id,account_name,password,salt,creat_time,last_lgin_time) values('".$account_id."', '".$account_name."', '".$new_password."', '".$salt."', '".$create_time."', '".$last_login_time."')"); $user_id = uniqid(); $result1 = mysql_query("INSERT INTO app_user(user_id,username,account_id) VALUES('".$user_id."', '".$account_name."', '".$account_id."')"); if ($result){ $json = json_encode(array( "resultCode"=>200, "message"=>"register successed!" )); echo($json); } }}//檔案上傳介面function upload(){}?>
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>
服務端接收檔案介面upload.php
upload.php
<?phprequire ("../connect_db.php");$conn = db_connect();mysql_query("set names 'utf8'");mysql_select_db("FECG");$file_name = $_POST["filename"];$userid = $_POST["userid"];$heart_rate = $_POST["rate"];if ($_FILES['filename']['name'] != NULL){ if ($_FILES['filename']['error']){ $data = array( "resultCode"=>1, "message"=>"失敗,上傳檔案出錯!" ); echo json_encode($data); } else{ //擷取檔案尾碼名 $file_extension = substr(strrchr($_FILES['filename']['name'], '.'), 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 = '/var/www/html/FECG/fecg_segment_data/'.$userid.'/'.date("YmdHis").".".$file_extension; if (is_uploaded_file($_FILES['filename']['tmp_name'])){ $result = move_uploaded_file($_FILES['filename']['tmp_name'], $file_path); if ($result){ //檔案上傳成功,進行第二步更新資料庫 $result = mysql_query("SELECT * FROM app_account WHERE account_name='".$userid."'"); 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='".$account_id."'"); $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('Y-m-d H:i:s'); $result = mysql_query("INSERT INTO ecg_segment(ecg_segment_id,channel,heart_rate,ecg_url,user_name,user_id) VALUES('".$ecg_segment_id."', '".$channel."', '".$heart_rate."', '".$file_path."', '".$user_name."', '".$user_id."')"); $task_id = uniqid(); $server_analysis = "異常"; $result1 = mysql_query("INSERT INTO task(task_id,creat_time,server_analysis,ecg_segment_id) VALUES('".$task_id."', '".$create_time."', '".$server_analysis."', '".$ecg_segment_id."')"); 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);}?>
(上述代碼都是根據本人項目需要開發的相應介面)