Table of Contents
1. Introduction to APP interface
2. PHP interface knowledge
JSON and XML methods encapsulate the communication interface
3. Actual development examples
Home Backend Development PHP Tutorial PHP server development APP interface

PHP server development APP interface

Apr 26, 2018 pm 02:42 PM
php blog

This article introduces the development of APP interface on PHP server. Now I will share it with you. Friends who are interested can take a look.


1. Introduction to APP interface


What is app interface? The app interface is a script written in a server-side program such as PHP for the app client to request and obtain data. For example, the homepage of a store app must have some product lists, so when you open the app, the homepage encapsulated in the app will actually request a remote php file such as: http://www.example.com/index .php to obtain the product list data that needs to be displayed on the home page. When front-end engineers get this data, they will display the content according to a specific design.
This is the purpose of the interface. An app usually needs to access multiple PHP interfaces to obtain different data. Let's talk about the interface implementation process in detail and some core technologies needed to implement the interface.


2. PHP interface knowledge

JSON and XML methods encapsulate the communication interface

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;
    }
}
Copy after login

response.class.php It is the simplest class that returns data in json or XML format.
The interface file code is posted below:
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);
Copy after login

3. Actual development examples

  • Develop three interfaces (login, registration, file upload) to complete the corresponding functions respectively

  • Because I do not do APP development, during the actual interface testing process, use The RESTClient extension of the Firefox browser simulates APP requesting services and receiving data
    (1) Writing of login and registration interfaces
    Direct code:

<?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(){}?>
Copy after login

RESTClient test:
PHP server development APP interface
(Registration is a similar operation)
(2) File upload
Because it is a simulation, and the file upload interface involves file upload, RESTClient cannot simulate it. So write a separate client uploadClient.html to simulate file upload.
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>
Copy after login

The server receives the file interface 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);
}?>
Copy after login

(The above codes are all corresponding interfaces developed according to the needs of my project)

Related recommendations:

The clearest graphic tutorial on building a PHP server environment

Qiniu Cloud Storage-PILI Live PHP Server How to introduce SDK code into your own project?

Enhanced version of communication process design between mobile terminal and PHP server interface


The above is the detailed content of PHP server development APP interface. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles