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('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 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);
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 '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 test:
(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>
The server receives the 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 ($_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); }?>
(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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use