Home Backend Development PHP Tutorial PHP development of high availability and high security app backend study notes

PHP development of high availability and high security app backend study notes

Apr 08, 2018 am 09:33 AM
php rear end study

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

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

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

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!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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.

See all articles