PHP Server Development App Interface

Source: Internet
Author: User
Tags php server
This article is about the PHP server Development app interface, now to share with you, interested friends can see


Introduction of App Interface


What is an app interface? An app interface is a script that is written in a server-side program, such as PHP, to get data from an app client request. For example, a shop App home page, there must be some product list, then when you open the app, this package in the app's home page will actually go to request a remote PHP file such as: http://www.example.com/index.php To get the product list data that needs to be displayed on the home page. When the front-end engineer gets this data, it will show it in a specific design.
This is what the interface is intended to accomplish. Within an app, it's often necessary to access multiple PHP interfaces to get different data. The following is a detailed talk about the process of interface implementation and some of the core technologies required to implement the interface.

Second, PHP interface knowledge

JSON and XML encapsulation of communication interfaces

response.class.php

<?php/** *description The class that returns the specified data format * @param the status code returned by the $code [int] * @param the status information returned $message [string] * @param $data [array] Required The data to be returned * */class response{public Function json ($code, $message, $data) {$result = array ("Code" =& Gt        $code, "message" = $message, "data" = $data);    Return Json_encode ($result);                The 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;        /** * Parse data into XML string */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 is the simplest class to return JSON or XML-formatted data
Paste the following interface file code:
returndata.php

<?phprequire "response.class.php";    Introduce return information class//Prepare return data $code = $; $message = "Information request succeeded"; $data = Array (        "name" = "Ruanwnewu",        "sex" =  "1", c4/> "Age" = "+"  ,        "exp" = = Array ("" + "                =" Beijing Rui Tai New "," ~ "and"                brother Lian ",                " all "=" (Wood ant Technology "            )    );//Instantiate response class $response = new response;//return data echo $response JSON ($code, $message, $data);

Iii. Examples of practical development

    • Development of three interfaces (login, registration, file upload), to complete the corresponding function

    • Because I do not do app development, so in the actual interface testing process, the use of Firefox browser restclient extension simulation app request service and receive data
      (1) Writing of login and registration interface
      Directly on the code:

<?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;}    Login interface 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"]) {//Login succeeded $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 PA            ssWOrd is wrong!please try again. "));         Echo ($json); }}else{//Login Failed $json = Json_encode (Array ("ResultCode" =>500, "message" =              "Please register!"        ));    Echo ($json);    }}//Register Interface Function Register () {$account _name = $_post["username"];    $password = $_post["password"];    $result = mysql_query ("select * from App_account where account_name= '". $account _name. ""); Query failed if (! $reSult) {$json = Json_encode (Array ("ResultCode" =>500, "message" = "Select Failed!"        ));    Echo ($json); }//Username registered if (mysql_num_rows ($result) > 0) {$json = Json_encode (Array ("ResultCode" =>500        , "message" = "Register failed!"));    Echo ($json);        }else{//Insert record into database $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 (); $result 1 = 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" = "Re           Gister successed! "));        Echo ($json); }}}//File Upload interface function upload () {}?>

Restclient Test:

(registration is a similar operation)
(2) File upload
Because it is a simulation, and the file upload interface involves uploading files, restclient cannot be simulated. So write a separate client uploadclient.html to simulate file uploads.
Uploadclient.html

<! DOCTYPE html>

Server Receive file Interface 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 ($_file        s[' filename ' [' ERROR ']) {$data = Array ("ResultCode" =>1, "message" = = "failed, error uploading file!")        );    echo Json_encode ($data);        } else{//Gets the file suffix name $file _extension = substr (STRRCHR ($_files[' filename ' [' name '], '. '), 1);        Determine if the folder exists $path = "/var/www/html/fecg/fecg_segment_data/". $userid; if (!file_exists ($path)) {//Create a folder named with User name if (mkdir ($path)) {$data = array ("message" =&G t; "               OK ");        echo Json_encode ($data);} }//Name the uploaded file $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) {//File upload is successful, the second step is to update the database $result = mysql_query ("select * FROM App_account WHERE acc                Ount_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"];                $result 1 = mysql_query ("select * from App_user WHERE account_id= '". $account _id. "");                $row 1 = mysql_fetch_array ($result 1, MYSQL_ASSOC);                $user _id = $row 1["user_id"];                $user _name = $row 1["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 = "Exception";                                      $result 1 = 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                    "= =" File Upload succeeded! ");                echo Json_encode ($data);       } else{$data = Array (                 "ResultCode" =>3, "message" = "Server Error!");                echo Json_encode ($data); }} else{$data = Array ("ResultCode" =>4, "M                Essage "=" uploaded failed! ");            echo Json_encode ($data); }} else{$data = Array ("ResultCode" =>5, "message" = "=" File upload failed!)            "            );        echo Json_encode ($data);    }}}else{$data = Array ("ResultCode" =>300, "message" = "file name cannot be empty!"); echo Json_encode ($data);}? >

(The code above is the corresponding interface developed according to my project needs)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.