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

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

不言
不言Original
2018-04-08 09:33:535174browse

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!

Statement:
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