


PHP development of high availability and high security app backend study notes
This article shares with you study notes on developing high-availability and high-security app backends in PHP. Friends in need can refer to the content of the article
Source code download address: https://download.csdn .net/download/qq_21683643/10331534
Directory
1.Security
2.Authorization code sign algorithm
3.Login scenario access_user_token algorithm
4.Token unique Sexual support
5.API one-time request support
6.High availability
7.Restful API
8.Similarities and differences between web login and APP login
9.Alibaba SMS verification solution client APP complex login scenario
10.API interface version solution
11.APP local time and server time consistent solution
12.Unpredictable API internal exception solution
13.APP version upgrade solution
14. Use Qiniu Cloud to solve the basic service capabilities of image processing
15. Encapsulation of basic class libraries
16. Penetration of PHP design patterns
17. Some modules provide multiple solutions for final selection The optimal solution
18. Asynchronous data interaction between PHP and ajax
1, restful api
Data structure format
3. HTTP status code is implemented using TK’s own json
3. status business status code
4. message prompt message
5. data data layer
Universal API interface data encapsulation
function show($status, $message, $data=[], $httpCode=200) { $data = [ 'status' => $status, 'message' => $message, 'data' => $data, ]; return json($data, $httpCode); }
Unpredictable internal exception api data output solution
config configure exception_handle to fill in the exception class path
class ApiHandleException extends Handle { /** * http 状态码 * @var int */ public $httpCode = 500; public function render(\Exception $e) { // 还原正常报错,上线后为flase(服务端开发) if(config('app_debug') == true) { return parent::render($e); } if ($e instanceof ApiException) { $this->httpCode = $e->httpCode; } return show(0, $e->getMessage(), [], $this->httpCode); } }class ApiException extends Exception { public $message = ''; public $httpCode = 500; public $code = 0; /** * @param string $message * @param int $httpCode * @param int $code */ public function __construct($message = '', $httpCode = 0, $code = 0) { $this->httpCode = $httpCode; $this->message = $message; $this->code = $code; } }
2. APP-API data security solution
The solution is various encryption: MD5 AES (symmetric encryption) RSA (asymmetric, low efficiency)
sign (valid time, uniqueness)
/** * 生成每次请求的sign * @param array $data * @return string */ public static function setSign($data = []) { // 1 按字段排序 ksort($data); // 2拼接字符串数据 & $string = http_build_query($data); // 3通过aes来加密 $string = (new Aes())->encrypt($string); return $string; }/** * 检查sign是否正常 * @param array $data * @param $data * @return boolen */ public static function checkSignPass($data) { $str = (new Aes())->decrypt($data['sign']); if(empty($str)) { return false; } // diid=xx&app_type=3 parse_str($str, $arr); if(!is_array($arr) || empty($arr['did']) || $arr['did'] != $data['did'] ) { return false; } // 有效时间:时间间隔不能超过60s if(!config('app_debug')) { if ((time() - ceil($arr['time'] / 1000)) > config('app.app_sign_time')) { return false; } //echo Cache::get($data['sign']);exit; // 唯一性判定 if (Cache::get($data['sign'])) { return false; } } return true; }/** * 检查每次app请求的数据是否合法 */ public function checkRequestAuth() { // 首先需要获取headers $headers = request()->header(); // todo // sign 加密需要 客户端工程师 , 解密:服务端工程师 // 1 headers body 仿照sign 做参数的加解密 // 2 // 3 // 基础参数校验 if(empty($headers['sign'])) { throw new ApiException('sign不存在', 400); } if(!in_array($headers['app_type'], config('app.apptypes'))) { throw new ApiException('app_type不合法', 400); } // 需要sign if(!IAuth::checkSignPass($headers)) { throw new ApiException('授权码sign失败', 401); } Cache::set($headers['sign'], 1, config('app.app_sign_cache_time')); // 1、文件 2、mysql 3、redis $this->headers = $headers; }
Solution for time consistency between APP and server
Solution 1: Get the server time, and the client gets the correct time from the server for comparison.
Solution 2: Transmit timestamp when initializing the app, client time = server timestamp + difference
3. API interface document writing (API input parameter, output parameter format)
API interface address Request method Post input parameter format Output parameter format http code
4. APP version upgrade business development
Table design
CREATE TABLE ent_version
( id
int(10) unsigned NOT NULL, app_type
varchar(20) NOT NULL DEFAULT ” COMMENT 'app type such as ios android', version
int(8) unsigned NOT NULL DEFAULT '0' COMMENT 'Internal version number', version_code
varchar(20) NOT NULL DEFAULT ” COMMENT 'External version number such as 1.2. 3', is_force
tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'Whether to force update 0 no, 1 force update', apk_url
varchar(255 ) NOT NULL DEFAULT ” COMMENT 'apk latest address', upgrade_point
varchar(500) NOT NULL DEFAULT ” COMMENT 'upgrade prompt', status
tinyint(1) NOT NULL DEFAULT '0' COMMENT 'status', create_time
int(10) unsigned NOT NULL DEFAULT '0', update_time
int(10) unsigned NOT NULL DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
5. Login development
1.1 Introduction to APP login business development
General apps have two states : Login state and non-login state
Why do you need to log in? Mining users, interaction and communication
How to log in to the APP? Imitate other App login
Other login methods: password-free mobile phone number verification code, account password
Third-party login methods: QQ authorization, WeChat authorization, Weibo authorization
1.2 Design of App login table structure
CREATE TABLE ent_user
( id
int(10) unsigned NOT NULL COMMENT 'primary key', username
varchar(20) NOT NULL DEFAULT ” COMMENT 'username', password
char(32) NOT NULL DEFAULT ” COMMENT 'password', phone
varchar(11) NOT NULL DEFAULT ” COMMENT 'mobile phone number', token
varchar(100) NOT NULL DEFAULT ” COMMENT 'token', time_out
int(10) unsigned NOT NULL DEFAULT '0' COMMENT ' Token expiration time', image
varchar(200) NOT NULL DEFAULT ” COMMENT 'avatar', sex
tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT 'Gender 0 male and 1 female', signature
varchar(200) NOT NULL DEFAULT ” COMMENT 'Personal signature', create_time
int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Registration time', update_time
int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'Login time', status
tinyint(1 ) NOT NULL DEFAULT '0' COMMENT 'Is the status locked'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1.3 Introduction to Alibaba Cloud Communication Service Platform
What is Alibaba
Alibaba provides Including personalized services such as text messages and voice calls
1.4 Development of the function of sending SMS verification codes
1.5App login token uniqueness algorithm
App calls login, and the server returns encrypted token information. Every time the app requests the interface, it needs to bring the token
App generates a unique token and encrypts it: token=token+13 Bit timestamp
1.6App login by password
Both username and password need to be encrypted and transmitted to the server
6, APP side exception, performance monitoring and positioning analysis
Basic situation of exceptions on the APP side:
Crach A sudden crash occurred during the use of the App
Stuck and screen lag
Exception Abnormality in the program
ANR A pop-up box prompting no response appears (Android)
Data collection plan:
Establish an exception performance table and develop an API interface
id primary key
app_type app type
version_code version number
Model device model
Did device id
Type exception type
Descripting description
Line errors
Create_time Create time
Mature solution:
Using a third -party platform, the APP client can be connected to the SDK. Statistical data, such as: Umeng statistics
7, APP message push service solution
Polling method: APP regularly sends http requests to the server to see if there is any message
Third-party platform: Server->Third-party platform->app
Related recommendations:
Some PHP development security issues compiled
PHP Detailed explanation of Session development principles and usage
The above is the detailed content of PHP development of high availability and high security app backend study notes. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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,

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

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 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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.
