PHP Development High-availability high-security app backend learning notes

Source: Internet
Author: User
Tags local time

This article to you to share is the PHP development of high-availability high-security app back-end of the study notes, the need for friends can refer to the content of the article

Source code Download Address: https://download.csdn.net/download/qq_21683643/10331534
Catalogue
1. Security
2. Authorization Code sign algorithm
3. Login Scene Access_user_token algorithm
4.token Single-Sex support
5.API one-time request support
6. High Availability
7.Restful API
8.web Login and App login similarities and differences
9. Ali larger than 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 Scenario
14. Using seven cow cloud to solve the image processing basic service capability
15. Encapsulation of the base class library
16.PHP Penetration of design patterns
17. Some modules provide a variety of solutions and finally choose the best solution
Asynchronous data interaction for 18.PHP and Ajax

1. RESTful API
Data structure format
3. HTTP status code using the TK-enabled JSON implementation
3. Status Code of Business
4. Message Hint message
5. Data layer
Generalized 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 configuration Exception_handle fill in exception class path

Class Apihandleexception extends  Handle {    /**     * HTTP status code     * @var int */public    $httpCode = 500;< C6/>public function render (\exception $e) {        //restore normal error, on-line after the Flase (server development)        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 = $;    Public $code = 0;    /**     * @param string $message     * @param int $httpCode     * @param int $code */public    function __cons Truct ($message = ", $httpCode = 0, $code = 0) {        $this->httpcode = $httpCode;        $this->message = $message;        $this->code = $code;    }}

2, APP-API Data security solution
Solution is a variety of encryption: MD5 AES (symmetric encryption) RSA (asymmetric, less efficient)
sign (validity time, uniqueness)

/** * Generates sign * For each request @param array $data * @return String */public static function setsign ($data = []) {        1 Sort by field ksort ($data);        2 stitching string Data & $string = Http_build_query ($data);        3 Encrypt with AES $string = (new Aes ())->encrypt ($string);    return $string; }/** * Check if sign is normal * @param array $data * @param $data * @return Boolen */public static function ch        Ecksignpass ($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; }//Valid time: The interval cannot exceed 60s if (!config (' App_debug ')) {if (Time ()-Ceil ($arr [' time ']/+) &G T            Config (' app.app_sign_time ')) {return false; }//echo Cache::get($data [' sign ']); exit;            Uniqueness Determination if (Cache::get ($data [' sign ')]) {return false;    }} return true; }/** * Check that the data requested by each app is legitimate */Public function Checkrequestauth () {///First need to get headers $headers = Reque        St ()->header (); TODO/sign encryption requires client engineer, decryption: service-side engineer//1 headers body follow sign to do the addition and decryption of parameters//2//3//        The base parameter check if (Empty ($headers [' Sign '])} {throw new Apiexception (' sign does not exist ', 400); } if (!in_array ($headers [' app_type '], config (' app.apptypes ')) {throw new apiexception (' app_type illegal ', 40        0); }//Need sign if (!        Iauth::checksignpass ($headers)) {throw new apiexception (' Authorization code sign failed ', 401);        } cache::set ($headers [' sign '], 1, config (' app.app_sign_cache_time '));    1, File 2, MySQL 3, redis $this->headers = $headers; }

App and server-side time consistency solutions
Resolution 1: Get the server time, the client to the server to compare the correct time.
Resolution 2: Transfer timestamp when initializing app, client time = Server timestamp + difference
3. API Interface Document writing (API entry, parameter format)
API interface Address request mode post in parameter format HTTP code
4, App version upgrade business development
Design of the table
CREATE TABLEent_version(
idInt (ten) unsigned not NULL,
app_typevarchar (+) not NULL DEFAULT ' COMMENT ' app type such as iOS Android ',
versionInt (8) unsigned not NULL DEFAULT ' 0 ' COMMENT ' build number ',
version_codevarchar () not NULL DEFAULT "COMMENT ' external version number such as 1.2.3 ',
is_forcetinyint (1) unsigned not NULL DEFAULT ' 0 ' COMMENT ' is forced to update 0 No, 1 force update ',
apk_urlvarchar (255) Not NULL DEFAULT "COMMENT ' apk latest address ',
upgrade_pointvarchar (+) not NULL DEFAULT ' COMMENT ' upgrade hint ',
statustinyint (1) Not NULL DEFAULT ' 0 ' COMMENT ' state ',
create_timeInt (ten) unsigned not NULL DEFAULT ' 0 ',
update_timeInt (ten) unsigned not NULL DEFAULT ' 0 '
) Engine=innodb auto_increment=3 DEFAULT Charset=utf8;
5. Login Development
1.1APP Login Business Development Introduction
The General app has two states: Login and non-logged
Why do I have to log in? Tap users, interact, communicate
How to do app login? Impersonate another app to sign in
Other login methods: password-free mobile phone number verification code, account code
Third-party Login method: QQ Authorization, authorization, Weibo authorization
Design of 1.2APP Login table structure
CREATE TABLEent_user(
idInt (ten) unsigned not NULL COMMENT ' primary key ',
usernamevarchar () not NULL DEFAULT ' COMMENT ' username ',
passwordchar (+) not NULL DEFAULT "COMMENT ' password ',
phonevarchar (one) not NULL DEFAULT "COMMENT ' phone number ',
tokenvarchar (+) not NULL DEFAULT ' COMMENT ' token ',
time_outInt (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' token expiration Time ',
imagevarchar (+) not NULL DEFAULT "COMMENT ' Avatar ',
sextinyint (1) unsigned not NULL DEFAULT ' 0 ' COMMENT ' sex 0 male 1 female ',
signaturevarchar (+) not NULL DEFAULT "COMMENT ' personality signature ',
create_timeInt (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' Registration time ',
update_timeInt (ten) unsigned not NULL DEFAULT ' 0 ' COMMENT ' login Time ',
statustinyint (1) Not NULL DEFAULT ' 0 ' COMMENT ' state is locked '
) Engine=innodb DEFAULT Charset=utf8;
1.3 Ali is more than cloud communication Service platform Introduction
What is Ali greater than
Ali is more than provides personalized services including SMS, voice, etc.
1.4 Send SMS Verification code function development

1.5APP Login Token Uniqueness algorithm
App Call login, the server returns encrypted token information, each app request interface requires token
App generates a unique token and encrypts: token=token+13 bit timestamp
1.6APP Login by password
Both the username and password need to be encrypted for transmission to the server.

6, App-side anomaly, performance monitoring and location analysis
App-side exception basic situation:
Crach a sudden flashback during app use
The lag of the screen
The exception that occurs with the Exception program
ANR pop-up prompt unresponsive bullet box (Android)
Data collection Scenarios:
Create an Exception performance table and develop API interfaces
ID PRIMARY Key
App_type app Type
Version_code Version number
Model Equipment Model
Did device ID
Type Exception types
Description description
Line number of lines in error
Create_time creation Time
Proven Solutions:
With third-party platforms, app clients access the SDK to statistics, such as: Friends League statistics
7, App message push service solution
Polling method: The app periodically sends HTTP requests to the server for a message
Third-party platform: server-side third-party platform->app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.