PHP interview summary


Continuously update….


1. Briefly describe the in PHPautoload

AutoloadLoading mechanism,When instantiating a class through new, PHP will load the corresponding file through the defined autoload function, if the class file uses extensions or implements and needs other class files, PHP will rerun autoload to find and load the class file. If there are two requests for the same class file, an error will be reported.

2. What are the advantages and disadvantages of static variables?

Characteristics of static local variables:
1. It will not change with the call and exit of the function.
2. Static local variables are initialized only once.
3. Static attributes can only be initialized to a character value or a constant, and expressions cannot be used.
4. When a function is called multiple times and the value of some variables is required to be reserved between calls, static local variables can be considered.

3. strtrandstr_replaceWhat’s the difference and what scenarios are they used in?

  • str_replace()Replace some characters in the string with other characters (case sensitive)
  • strtr()Converts a specific character in a string.

Version 5.6 str_ Replace is 10 + times more efficient than strtr. The efficiency of version 7.0 is basically the same, but the str of 5.6_ Replace is three times higher than 7.0

4. Magic method

  • __construct()If the default constructor of the class:__ When construct () and a method with the same name as the class appear together, it is called by default__ Construct () instead of a method with the same name.
  • __call(): called when a method that does not exist or is inaccessible is called__ Call ($name, $arguments) method.
  • __toString(): called directly when printing an object.
  • __clone(): called directly when the object is copied.
  • __isset(): when isset() or empty() is used for non-existent or inaccessible attributes__ Isset() will be called;
  • __destruct(): the destructor of a class, which is executed when all references of the object are deleted or the object is explicitly destroyed.
  • __sleep()Called when the serialize() function is executed

5. As shown below, what results will be output?

foreach ($array as $key => $item) {
            $array[$key + 1] = $item + 2;
            echo "$item";

Examples of results:$array = [3,6,7,8];

3678 // echo outputs the values of the elements in the array
    [0] = > 3 // $key remains unchanged
    [1] = > 5 // each time, $ekY + 1, the corresponding value plus 2,
    [2] => 8
    [3] => 9
    [4] => 10

6. Limit the number of recursions

Recursion is aA mechanism by which a function calls itself (directly or indirectly), this powerful idea can make some complex concepts extremely simple. Logical recursion can be unlimited, but the language executor or program stack will limit the number of recursions
PHP manual note: however, avoid recursive function / method calls exceeding 100-200 layers, because it may crash the stack and terminate the current script. Infinite recursion can be considered a programming error.

  • Two basic conditions of recursion

    • Recursive exit condition, this is a necessary condition for the normal execution of recursion and the correct return of recursion. Without this condition, recursion will proceed indefinitely until the resources given by the system are exhausted. If you encounter “Max nest level of 100 reached” (in PHP, exceeding the recursion limit), there is no correct exit condition, resulting in excessive recursion depth or infinite recursion.
    • Recursive process。 Recursion of function calls from one layer to the next.

7. The difference between single quotation marks and double quotation marks

  • Double quotation mark internal variables will be parsed, single quotation mark will not be parsed
  • Special characters (\ R \ N and the like) in double quotation marks will be escaped, and the contents in single quotation marks will not be escaped.
  • Execution efficiency: the content in the single quotation mark string is always regarded as ordinary characters, so the content in the single quotation mark will not be escaped, so it is more efficient.

8. Array array sorting and de duplication;

For example: $arr = [10,4,6,4,19,3,5];

  • 1、 array_multisortIt can be used to sort multiple arrays at a time, or sort multidimensional arrays according to one or more dimensions.
  • 2. Idea: I think of sorting algorithm (such as bubbling) + de duplication functionarray_unique


function bubbleSort(array $arr){
        $count = count($arr); // Array length
        for($i = 1;$i < $count;$i++){
            for ($k = 0;$k < $count - $i;$k++){
                if ($arr[$k] > $arr[$k+1]){
                    $temp = $arr[$k];
                    $arr[$k] = $arr[$k+1];
                    $arr[$k+1] = $temp;
        return array_unique($arr);

9. What is object orientation?

It is not only a programming paradigm, but also a programming method. It takes the object as the basic unit of the program and encapsulates the program and data to improve the reusability, flexibility and scalability of the software.

10. Differences and relationships between classes and objects

  1. A class is a template that defines a series of attributes and operations, while an object concretizes the attributes and then gives them to the class for processing.
  2. An object is data, and the object itself does not contain methods. But the object has a “pointer” to a class in which there can be methods.
  3. Class and object are inseparable. If there is an object, there must be a class corresponding to it. Otherwise, the object will become a child without relatives (there is a special situation, which is caused byScalar cast object, there is no class and its object. At this point, one in PHP is called “orphan”stdClassClass will host this object).

11. The difference between for and foreach

1、foreachAlso called enhancementforCycle,foreachActuallyforA special simplified version of the loop.
2、foreachApplicable to traversal of only sets or arrays,forIt is more efficient in more complex cycles.
3、foreachYou cannot modify an array or collection (add or delete). If you want to modify it, useforCycle.
So by comparisonforThe cycle is more flexible.

12. What is the difference between include and require statements?

  • Both include and require import the specified file. Plus_ Once means that it is imported only once, and those already imported will not be imported.
  • Include generates a warning when importing a non saved file and the script will continue to execute. Require will cause a fatal error and the script will stop executing.
  • Include has a return value, but require does not.

The use of the two is different:

  • The require function is usually placed at the front of the PHP program. Before the PHP program is executed, it will first read the imported file specified by require and make it a part of the PHP program web page. Common functions can also be introduced into web pages in this way.
  • The include function is usually placed in the processing part of process control. The PHP program web page reads the include file only when it reads it. In this way, the process of program execution can be simplified.

13、isset()、empty()、is_ What’s the difference between null()?

  • Is when the variable is undefined_ Null () is not allowed to be judged as a parameter, and a notice warning error will be reported;
  • Empty and isset will first check whether the variable exists, and then detect the value of the variable. And is_ Null just directly checks whether the variable value is null, so if the variable is not defined, an error will occur!
  • Isset(): returns false only if null and undefined;
  • Empty(): “”, 0, “0”, null, false, array(), undefined, all return false;
  • is_ Null (): only judge whether it is null, and no warning is defined;
  • The variable itself is used as a parameter, which is consistent with empty(), but when an undefined variable is accepted, a warning is reported;
  • “Empty”, “0”, “0”, null, false, array (), empty() and “variable itself as a parameter” have the same results, which are treated as “null”, while isset() and is()_ Null () is treated as “null” only if it is null (note that false is not considered null)

14. Common PHP array functions and their functions

array_values($ARR): get the value of the array
array_keys($ARR): get the key name of the array
array_flip($ARR): the value in the array is interchangeable with the key name (if there is a repetition, the previous one will be overwritten by the later one)
in_array(‘Apple’, $ARR): Retrieves apples from the array
array_search(“apple”, $ARR): retrieves the apple in the array, and returns the key name if it exists
array_push($arr, “apple”, “pear”): press one or more elements into the end of the array stack (stack), and return the number of stacked elements
array_pop($ARR): pop the last element of the array stack (out of the stack)
array_shift($ARR): the first element in the array is moved out and returned as a result (the length of the array is reduced by 1, other elements are moved forward by one bit, the numeric key name is changed from zero technology, and the literal key name remains unchanged)
array_unshift($arr, “a”, array (1,2)): insert one or more elements at the beginning of the array

15. PHP print the date of the previous day (Format: 2015-01-01 11:11:00)

 echo date('Y-m-d H:i:s',strtotime('-1 day',time()));

16. PHPerror_reportingFunction function

error_ Reporting () sets the error reporting level of PHP and returns the current level.

17. Write a function to extract the file extension from a standard URL as efficiently as possible, such as…PHP and php

function getExt2($url)
   $urlinfo = pathinfo($url);

    if(strpos($urlinfo['extension'],'?') !== false)
      return explode('?',$urlinfo['extension'])[0];
      return $urlinfo['extension'];
  return 'no extension';

18. Implement a string inversion function

public function strrev($str)
    $newstr = '';
    $len = strlen($str); // Get string length
    for($i = $len; $i >= 0; $i--)
        $newstr .= $ str{$i}; // From the maximum subscript to the minimum, it is reversed
    return $newst;

19. Write commonHTTP status codeAnd its function

Name Academy score
200 OK Request succeeded, the server returned the web page successfully
301 Moved Permanently Permanent jump, the requested page has been permanently redirected to a new location.
403 Forbidden No access, the server rejected the request
404 Not Found The server could not find the requested page
500 Internal Server Error Server internal error
502 Bad Gateway Bad Gateway Generally, when the gateway server requests the back-end service, the back-end service does not return the result correctly according to the HTTP protocol.
503 Service Unavailable The service is currently unavailable, possibly due to overload or shutdown maintenance.
504 Gateway Timeout gateway timeout Generally, when the gateway server requests the back-end service, the back-end service does not complete the service within a specific time.

20. Write a function to verify whether the email format is correct

function check_email($email){

        $preg = "/^\w+([-_.]\w+)*@\w+([-_.]\w+)*(\.\w+){0,3}$/i";
        return $res;// 1 is returned for successful matching and 0 is returned for failed matching

21. Understanding of MVC

MVCIt is the abbreviation of model view controller. It is a software design model. It organizes code by separating business logic, data and interface display, and gathers business logic into one component. It does not need to rewrite business logic while improving and customizing interface and user interaction.

22. Difference between post and patch

23. PHP memory recycling mechanism

PHP’s memory management mechanism is to give a piece of space in advance to store variables. When the space is insufficient, apply for a new space.

  • 1. Store the variable name, and there is a symbol table.
  • 2. Variable values are stored in memory space.
  • 3. When deleting a variable, the storage space of the variable value will be released, and the symbol table of the variable name will not be reduced.

Although the memory becomes smaller after deletion, it is still larger than before the variable is not defined. This is because although the value of the variable is deleted, the variable name is not deleted.

PHP garbage collection mechanism

  • PHP variables are stored in a zval container
  • 1. Type 2 Value 3 is_ Ref stands for whether there is an address reference 4 Refcount points to the number of variables for this value

garbage collection:

  • 1. In version 5.2 or earlier, PHP will judge whether it is garbage according to the refcount value. If the refcount value is 0, PHP will release it as garbage. This recycling mechanism is flawed, and the variables referenced by the ring cannot be recycled
  • 2. After version 5.3, the garbage collection mechanism has been improved. If you find oneZval containerMediumrefcountIt is increasing, indicating that it is not garbage. If you find oneZval containerMediumrefcountIf it is reduced to 0, it will be directly recycled as garbage. If it is found that the refcount in a zval container is decreasing and not decreasing to 0, PHP will put the value into the buffer as a suspicious object that may be garbage. When the buffer reaches the critical value, PHP will automatically call a method to traverse each value. If it is found to be garbage, it will be cleaned up



1. Advantages and disadvantages of laravel compared with other frameworks

  • laravel

    • Advantages: the number of users is the first in the world, the documents are complete, the framework structure is clear, and a large number of third-party expansion packages are available for reference. It is suitable for collaborative development of large websites, and the development efficiency of the artisan development tool provided is high. Composer extension, automatic loading, middleware
    • Disadvantages: it is a little complex, and it is slower to start than the general framework; A large number of third-party packages are referenced, but in some scenarios, we only use some methods in the class, and the code is somewhat redundant
  • ThinkPHP

    • Advantages: lightweight PHP development framework, easy to use, rich Chinese documents; The compatibility of the framework is strong, and PHP4 and PHP5 are fully compatible; It is suitable for the development of small and medium-sized projects, with low learning cost and high community activity
    • Disadvantages: Ajax support is not very good; Lack of object-oriented design, version 5 is basically object-oriented, and there are few auxiliary tools related to the framework community; The directory structure is chaotic and needs to be sorted out;
  • Yaf

    • Advantages: compared with native PHP, the PHP framework developed in C language brings almost no additional performance overhead There is no need to compile. It is loaded when PHP starts and resident in memory Faster execution speed and less memory consumption
    • Disadvantages: for the extension of C, if there are loopholes in the program and the author does not update it in time, users can only watch the website humiliated or pray, or close the website without knowing C

2. Laravel dependency injection

Dependency injection, essentially through constructors or in some casesInject class dependencies into classes through setter methods。 Generally speaking, when a model is introduced into a class many times, it can be introduced in the constructor at one time, and the methods in the class can be called directly.

3. Principle of dependency injection

  • The dependency injection principle uses class method reflection to obtain the parameter type, and then uses the container to construct the instance. Then use the callback function to start.
  • The injected object constructor cannot have parameters. Otherwise, an error will be reported. Missing argument 1
  • Dependency injection is good, but it must be invoked by the router class, otherwise it cannot be injected directly by new. So this is why only controller and job classes can use this feature.

4、 Composer

ComposerIs a cross platform PHP dependency management tool. Give WayComponent programmingWhen writing software, it’s like splicing LEGO toys. It greatly improves the efficiency of development and the reusability of code, and liberates the productivity.

Laravel uses composer as an extension package management tool.

5. Laravel life cycle

  • All request entries of the laravel application arepublic/index.phpDocuments.index.phpFile loadingComposerGenerated auto load settings, and then frombootstrap/app.phpThe script obtains the laravel application instance. The first action of laravel is to createService container instance
  • Request sent toHTTPKernel orConsoleKernel (used to process web requests and artisan commands respectively), which depends on the type of request entering the application.
  • One of the most important actions during kernel startup is to load applicationsService provider, all service providers of the application are configured inconfig/app.phpConfiguration fileprovidersArray. First, all providersregisterMethod is called, and then after all providers are registered,bootMethod is called.
  • Once the application is started and all service providers are registered,RequestIt will be handed over to the router for distribution. The router will distribute the request to the route or controller, and run all the middleware specified by the route at the same time.

Service providerIt is the most critical part of starting the laravel application. After the application instance is created, the service provider is registered, and the request is handed over to the started application for processing. The whole process is so simple!


1. The difference between int (1) and int (10) in MySQL

int(M) Maximum display width m, the length stored in the database is 4 bytes. The maximum effective display width is 255. This optional display width is specified forFill the width from the left when the display width is less than the specified column width。 The display width does not limit the range of values that can be saved in the column, nor does it limit the display of values that exceed the specified width of the column.

2. Left index principle:

  • Like, when matching a string, it does not start with a wildcard. The left side must be fixed before the field index will work
  • Composite index: when the field on the left is fixed, the index on the right is valid when the index matches. Because composite index keywords are sorted according to the fields on the left. If the fields on the left are the same, they are sorted according to the fields on the right.

3. Advantages and disadvantages of index creation:

  • advantage:

    • Creating indexes can improve system performance
    • The uniqueness index can ensure the uniqueness of each row of data in the database table
    • Speed up retrieval
    • Connection between accelerometers
    • When using grouping and sorting clauses for data retrieval, reduce the time of grouping and sorting in the query
    • By using the index, you can use the optimization Concealer in the query process to improve the system performance
  • Disadvantages:

    • Creating and maintaining indexes takes time, which increases with the increase of the amount of data
    • Physical space occupied by index
    • When adding, deleting and modifying the data in the table, the index needs dynamic maintenance, which reduces the speed of data maintenance

4. Please describe how MySQL master-slave servers synchronize data. What kind of SQL will cause the master-slave servers to fail to synchronize correctly?

  • Network delay

Due to MySQLMaster slave replication is an asynchronous replication based on binlog, the binlog file is transmitted through the network. Of course, the network delay is the vast majority of the reasons for the master-slave non synchronization. In particular, the probability of cross machine room data synchronization is very high. Therefore, separate reading and writing, and pay attention to the preliminary design from the business layer.

  • The loads of the master and slave machines are inconsistent

Since MySQL master-slave replication starts an IO thread from the master database, and starts an SQL thread and an IO thread from the master database, the load of any machine is very high and can’t be busy, resulting in insufficient resources of any thread and inconsistent master-slave.

  • max_ allowed_ Inconsistent packet settings

Master database settings abovemax_allowed_packetIt is larger than the slave database. When a large SQL statement can be executed on the master database, the slave database is set too small to be executed, resulting in inconsistent master-slave.

  • The key value from the self increment key is inconsistent with the self increment step setting, resulting in the inconsistency between the master and slave.
  • If sync is not set when MySQL is abnormally down_ Binlog = 1 or InnoDB_ flush_ log_ at_ trx_ If commit = 1, binlog or relaylog files are likely to be damaged, resulting in inconsistency between master and slave.
  • The master-slave synchronization caused by the bug of mysq l itself.
  • The versions are inconsistent. Especially when the higher version is the master and the lower version is the slave, the function supported on the master database is not supported on the slave database

5. There is an order table, as follows, to find the two users who have purchased the most times

order_id user_id goods
100000 100 Apple
100001 100 Apple
100002 101 a mandarin orange
100003 102 Apple
100004 102 Banana


SELECT order_id,user_id,COUNT(order_id) AS count FROM order GROUP BY user_id ORDER BY  count DESC  limit 2

6. Characteristics of transactions

  • Atomicity(Atomicity)

Atomicity means that all operations contained in a transaction either succeed or fail.

  • uniformity(Consistency)

Consistency means that a transaction must be in a consistent state before and after execution.

  • Isolation(Isolation)

Isolation is whenWhen multiple users access the database concurrentlyFor example, when operating the same table,The transactions opened by the database for each user cannot be disturbed by the operation of other transactions. Multiple concurrent transactions should be isolated from each other

  • persistence(Durability)

Persistence means that once a transaction is committed, the changes to the data in the database are permanent

7. Isolation level and high concurrency of transactions

  • If transaction isolation is not considered, several problems will occur:

    • Dirty reading(dirty read): refers to reading the data in another uncommitted transaction during one transaction.
    • Non repeatable reading(unrepeated read): for a data in the database, multiple queries within a transaction range return different data values. This is because it is modified and committed by another transaction during the query interval.
    • Unreal reading(phantom read): a transaction executes two queries. The second query has more or less data than the first, resulting in inconsistent results. It’s just that another transaction inserts or deletes data between the two queries.
    • Type I lost updates(lost update): when the transaction is not isolated at all, two transactions update the same data resource. If one transaction terminates abnormally, the first completed update will be lost at the same time.
    • Type II missing updates(second lost updates): it is a special case that cannot be read repeatedly. If two transactions read the same row, then both write and commit, the changes made by the first transaction will be lost.
  • Four transaction isolation levels:

  1. Serializable Serialization
  2. Repeatable Read Repeatable reading
  3. Read Commited Read Commited
  4. Read Uncommited read uncommited

  • Concurrency control:

    1. The database system adopts different lock types to realize the above four isolation levels, and the specific implementation process is transparent to users. Users are concerned about how to select the isolation level.
    2. For most applications, priority can be given to setting the isolation level of the database system to read committed, which can avoid dirty reading and has good concurrency performance.
    3. Each database connection has a global variable@@tx_isolationIndicates the current transaction isolation level. JDBC database connection uses the default isolation level of the database system.
    4. The isolation level can be set explicitly in the hibernate configuration file. Each isolation level corresponds to a positive integer.
    5. It should be noted that in the managed environment, if the database connection used by hibernate comes from the data source provided by the application server, hibernate will not change the transaction isolation level of these connections. In this case, you should modify the isolation level by modifying the data source configuration of the application server.
    6. When the database system adopts the red committed isolation level, it will lead to the concurrency problems of non repeatable reads and the second type of lost updates. When such problems may occur. Pessimistic or optimistic locks can be used in applications to avoid such problems.

MySQL view the current transaction isolation level:select @@tx_isolation
Set transaction isolation level:Set [global | session] transaction isolation level name;orset tx_ Isolation = 'isolation level name;'

8. Pessimistic lock and optimistic lock

  • Pessimistic lock

As its name implies, it refers to a conservative attitude towards data being modified by the outside world (including other current transactions of the system and transactions from external systems),In the whole process of data processing, the data is lockedImplementation of lock mechanism based on Database(only the locking mechanism provided by the database layer can truly ensure the exclusivity of data access. Otherwise, even if the locking mechanism is implemented in this system, it can not guarantee that the external system will not modify the data).
It is very easy to use pessimistic lock in Hibernate, but in practical application, pessimistic lock is rarely used, because it adds “for update” to tell the database to lock relevant data every time it sends SQL statements, which greatly reduces the costLimits concurrency, a large overhead of database performance

  • Optimistic lock

Optimistic locks are mostly implemented based on the data version recording mechanism. What is data version? That is, add a version ID to the data. In the version solution based on database tables, it is generally throughAdd a "version" field to the database table
Working principle of optimistic lock: when reading and taking out data, read this version number together, and then add one to this version number when updating later. At this time, compare the version data of the submitted data with the current version information of the corresponding record of the database table. If the version number of the submitted data is greater than the current version number of the database table, it will be updated, otherwise it will be considered as expired data.

9. Composite index

Concept: users canIndex on multiple columns, this index is called composite index (composite index);

Composite index needs less overhead during database operation and can replace multiple single indexes;
Narrow indexRefers to the index whose index column is 1-2 columns,Wide indexThat is, the index with more than 2 columns;
An important principle of designing indexes isCan use narrow index instead of wide index, because narrow indexes are often more effective than combined indexes;

10. Like optimization

Like is usually written asSelect cat from animal where name like '% cat%'
useexplainFrom the explanation, the SQL statement does not use an index (name has created an index), but a full table scan.

  • Try not to use itlike '%..%'
  • aboutlike '..%..'(does not start with%), forlike '%...'(not ending in%). Add a reverse function, and you can use the index again ‘(you need the support of reverse index)SQL> select * from test_like where reverse(object_name)like reverse('%AS');
  • uselocateFunction substitutionlike

    • Grammar oneLOCATE(substr,str)Return stringsubstrWhere the substring first appears in thestr
    • Grammar 2:LOCATE(substr,str,pos)returnsubstrstaystrThe position of the first occurrence in, ifsubstrstaystrDoes not exist in, the return value is0。 IfposExist, returnsubstrstaystrThe firstposThe position that first appears after the first position, ifsubstrstaystrDoes not exist in, the return value is0

MySQL optimization

  • SQL statement optimization
  • Index optimization
  • Choose the right storage engine
  • Select the appropriate data type for the field
  • Split the table horizontally or vertically
  • Optimization for storage engine
  • Disk I / O optimization
  • load balancing
  • Master-slave replication


1. How to detect web service slowness

  • Top: view system performance
  • Nginx: add the last field$request_time

List the pages whose PHP page request time exceeds 3 seconds, count the number of occurrences, and display the first 100
cat access.log|awk '($NF > 1 && $7~/\.php/){print $7}'|sort -n|uniq -c|sort -nr|head -100

  • Implemented in the code, the beginning write time and the end write time

2. Automatic script

crondIt is a daemon used to periodically execute certain tasks or wait for certain events under Linux.

  • System task scheduling: the work to be performed periodically by the system, such as writing cached data to the hard disk, log cleaning, etc. There is a crontab file in the / etc directory, which is the configuration file of system task scheduling.

*User task scheduling: work to be performed by users regularly, such as user data backup, regular email reminder, etc. Users can use crontab tool to customize their own scheduled tasks. All user-defined crontab files are saved in the / var / spool / cron directory. Its file name is consistent with the user name.
minute hour day month week command
You can also use the following special characters:

  • Asterisk (*): represents all possible values, such as the month field. If it is an asterisk, it means that the command is executed every month after the constraints of other fields are met.
  • Comma (,): you can specify a list range with comma separated values, for example, “1,2,5,7,8,9”
  • Middle bar (-): the middle bar between integers can be used to represent an integer range, for example, “2-6” means “2,3,4,5,6”
  • Forward slash (/): you can specify the interval frequency of time with forward slash. For example, “0-23 / 2” means to execute every two hours. At the same time, the forward slash can be used together with the asterisk, for example * / 10. If it is used in the minute field, it means to execute every ten minutes.

3. Nginx load balancing scheme

Common methods:

  • Round robin

According to the order in the nginx configuration file,Each request is allocated to a different back-end server in chronological order, if the back-end server goes down, it can be automatically eliminated.

upstream web { 
    server server1; 
    server server2; 
  • Minimum connection

The web request is forwarded toServer with the least number of connectionsCome on. least_ The conn algorithm is very simple. It is preferred to traverse the back-end cluster, compare the Conns / weight of each back-end, and select the back-end with the smallest value. If the Conns / weight values of multiple backend are the same as the minimum, then the weighted polling algorithm is adopted for them.

 upstream web { 
     server server1; 
     server server2; 
  • IP address hash

Continuous web requests from the same client may be distributed to different back-end servers for processing. Therefore, if session is involved, a load balancing scheme based on IP address hash can be used. In that case,Continuous web requests from the same client will be distributed to the same server for processing(each request is allocated according to the hash result of access IP, so that each visitor can access a back-end server regularly, which can solve the problem of session).

upstream web { 
    server server1; 
    server server2; 
  • Weighted load balancing

You can selectively distribute web requests according to the performance of the server. Specify the polling probability. The higher the weight, the greater the access ratio. Weight = 2, which means that for every three requests received, the first two requests will be distributed to the first server, and the third request will be distributed to the second server. Other configurations are the same as polling configuration.

upstream web { 
    server server1 weight=2; 
    server server2; 

Weight based load balancing and IP address hash based load balancing can be combined.

  • Fair (third party)

Requests are allocated according to the response time of the back-end server, and those with short response time are allocated first.

upstream web {
    server server1;
    server server2;
  • url_ Hash (third party)

The request is allocated according to the hash result of the access URL, so that each URL is directed to the same back-end server, which is more effective when the back-end server is cache. hash_ Method is the hash algorithm used

upstream web {

server server1:3128;
server server1:3128;
hash $request_uri;
hash_method crc32;


The status of each device is set to:
1. Down indicates that the server before the order does not participate in the load temporarily
2. Weight defaults to 1 The greater the weight, the greater the weight of the load.
3.max_ Failures: the number of times a request is allowed to fail. The default is 1 When the maximum number of times is exceeded, proxy is returned_ next_ Error in upstream module definition
4.fail_ timeout:max_ Pause time after failures.
5. Backup: when all other non backup machines are down or busy, request the backup machine. So this machine will have the lightest pressure. The sorry server provides non business functions.

4. Keepalived

KeepalivedIt is implemented through VRRP (Virtual Router Redundancy Protocol) protocolHigh availabilityFunctional. The purpose of VRRP is to solve the problem of single point of failure of static routing. It can ensure that the whole network can run continuously when individual nodes are down.

5. Difference between VI and VIM

They are allMultimode editorThe difference is that VIM is an upgraded version of VI. it is not only compatible with all instructions of VI, but also has some new features. These advantages of vim are mainly reflected in the following aspects:

  • 1. Multilevel undo

We know that in VI, pressing u can only undo the last command, while in VIM, you can undo it indefinitely.

  • 2. Ease of use

VI can only run in UNIX, while VIM can not only run on UNIX, windows, MAC and other operating platforms.

  • 3. Syntax highlighting

VIM can use different colors to highlight your code.

  • 4. Visual operation

In other words, VIM can run not only on the terminal, but also on X window, Mac OS and windows.

  • 5. Full compatibility with Vi

In some cases, you can use VIM as VI. VI and VIM are editors in Linux. The difference is that VIM is more advanced and can be regarded as an upgraded version of vi. VI is used for text editing, but VIM is more suitable for coding.

6. Awk command

AWKIt’s a kind ofLanguage for processing text files, is a powerful text analysis tool. Usually, awk is a part of a fileBehavior processing unitof Awk receives each line of the file and then executes the corresponding command to process the text.
Syntax:awk '{pattern + action}' {filenames}
patternRepresents the content found by awk in the data, andactionIs a series of commands executed when a match is found. Curly bracket({})They do not need to be present throughout the program, but they are used to group a series of instructions according to a specific pattern.patternIs the regular expression to be represented, enclosed by a slash.


1. Differences between RSA and AES:

  • RSA is asymmetric encryption, public key encryption, private key decryption, and vice versa. Disadvantages: it runs slowly and is not easy to implement in hardware. The length of the constant private key is 512bit, 1024bit, 2048bit and 4096bit. The longer the length, the more secure it is. However, the slower the generation of the key, the more time-consuming the encryption and decryption.
  • AES symmetric encryption, the longest key is only 256 bits, the execution speed is fast, and it is easy to implement in hardware. Because it is symmetric encryption, the key needs to be known by both sides of communication before transmission.
  • The length of AES encrypted data block must be 128 bits, and the key length can be any of 128 bits, 192 bits and 256 bits (if the data block and key length are insufficient, they will be supplemented)

summaryAsymmetric encryption algorithm is used to manage the key of symmetric algorithm, and then symmetric encryption algorithm is used to encrypt data. In this way, we integrate the advantages of two types of encryption algorithms, which not only realize the advantages of fast encryption speed, but also realize the advantages of safe and convenient key management.

2. A complete HTTP request explanation

  1. Enter the URL for the client.
  2. Client detection cache(if there is a cache and it is relatively new, the client directly reads the local cache for resource display. If there is a cache but it is not new, prepare the HTTP request package and send it to the server for cache verification).
  3. The first host of the extraction request passesDNS domain name resolutionGet the service IP (DNS cache recursion, etc.).
  4. Created via IP and default portTCP connection,Make HTTP requestMessage data transmission, which focuses on the description of three handshakes (the client sends syn to the server, the server sends syn and ack to the client, and the client sends syn, ACK and data to the server).
  5. The server program accepts the request, direct to the request path handler and prepare the HTTP response.
  6. Through the established TCP connectionreturndependenthttpResponse message and HTTP statusinformationThen, according to the actual situation, see whether to close the connection (keep alive of connection).
  7. TCP connection closedExperience 4 handshakes.
  8. clientGet the message information of HTTP response, and finally go through a series of front-end processing processesResources to be requestedconductExhibition

3. The difference and usage between cookie and session. Session lock

  1. The cookie data is stored on the client’s browser, and the session data is placed on the server
  2. Cookies are not very secure. Others can analyze the cookies stored locally and cheat them. Considering security, session should be used.
  3. The session will be saved on the server for a certain period of time. When access increases, it will occupy the performance of your server. Considering reducing the performance of the server, cookie should be used.
  4. The data saved by a single cookie cannot exceed 4K. Many browsers limit a site to save up to 20 cookies. (there is no limit on the amount of data stored in the session object, which can store more complex data types)
  • Session lock

PHP sessions are stored in files by default. When a PHP file (session_start()) that needs to operate a session is requested, this file will be locked by the process that operates the session first, causing other requests to be blocked. Other requests will be suspended in the session_ Start() until the s session file is unlocked. This ensures the order of read write and read write. It is ideal for data flow. However, in the current case of a large number of Ajax applications on pages, all requests are queued, which will greatly increase the time-consuming of page presentation, and even lead to unavailable faults such as request timeout.
solve: because the locked session file will not be unlocked until the script execution is completed or the session is closed normally, in order to prevent a large number of PHP requests (using $_sessiondata) from being locked, you can close it immediately after writing the session (usingsession_write_close()), which releases the lock;
Memcache or redis can solve the problem of “locking” by storing sessions, but if it is not handled properly, the number of connections will soar (if there is a time-consuming operation after the session operation, the connection will not be recycled. You can actively do the session_write_close() operation after the session write operation is completed);

4. XSS, CSRF, SSRF, SQL injection principle

  • XSSCross site scriptA security vulnerability attack of website application isCode injectionA kind of. It allows malicious users to inject code into web pages. It usually includes HTML and client scripting language.defenseAll uncertain (user input) contents directly output on the page are HTML escaped; Verify the format of user input content; Do not use uncertain content in script;
  • CSRF:Cross-site request forgery It’s a kind ofCoerce the user to perform unintended operations on the currently logged in web applicationAttack methods;Defense:Verify the HTTP referer field; Add a token in the request address (or HTTP header) and verify it;
  • SSRFThe simulation server made requests for other server resources without legitimacy verification。 Construct malicious intranet IP for detection, or use other supported protocols to attack other services. Defense: no jump, restricted protocol, intranet and Internet restrictions, URL restrictions. Bypass: use different protocols to bypass IP, IP format, add other characters to URL and malicious URL, @ and so on. 301 jump + DNS rebinding.
  • SQL injection: it is to deceive the server to execute malicious SQL commands by inserting SQL commands into the web form to submit or enter the query string of domain name or page request.defenseFiltering special symbols special symbol filtering or escape processing(addslashesFunction); Bind variables and use precompiled statements;

5. NPM and yarn concepts

NPM is node JS (a JavaScript running environment based on Google V8 engine) package management and distribution tool.

Yarn is a new package manager opened by Facebook in October 2016, which is used to replace the existing NPM client or other package management tools compatible with NPM warehouse. On the basis of retaining the original workflow characteristics of NPM, yarn makes it faster, safer and more reliable.


Mongodb data type:

  • String: the string in mongodb is UTF-8 valid.
  • Integer: stores numeric values. The integer can be 32-bit or 64 bit, depending on your server.

*Boolean: stores Boolean (true / false) values.

  • Arrays: stores an array or list or multiple values in a key.
  • Timestamp: stores the timestamp.
  • Object: embedded document.
  • Null (null): stores null values.
  • Date: stores the current date or time in UNIX time format.


1. Sorting algorithm

*Quick sort

Quick sort: I first select a ruler and use it to filter the whole queue to ensure that the elements on the left are not larger than it and the elements on the right are not smaller than it

function quickSort($arr){
  //Get array length
  $length = count($arr);
  //Judge whether the length needs to continue the binary comparison
  if($length <= 1){
    return $arr;
  //Define base element
  $base = $arr[0];
  //Define two empty arrays to store the results after comparison with the benchmark element
  $left = [];
  $right = [];
  //Traversal array
  for ($i=1; $i < $length; $i++) 
    //Compare with reference element
    if ($arr[$i] > $base) {
      $right[] = $arr[$i];
    }else {
      $left[] = $arr[$i];
  //Then recursively handle left and right respectively
  $left = quickSort($left);
  $right = quickSort($right);
  return array_merge($left,[$base],$right);
  • Bubble sorting

Idea: the method is as its name, just like bubbling, and a maximum number pops up from the array each time
For example: 2, 4, 1
4:2, 1, 4 for the first time
The second time, 2:1, 2, 4

function bubbleSort($arr){
  //Get array length
  $length = count($arr);
  //The first layer of circulation controls the bubbling rounds
  for ($i=0; $i < $length-1; $i++) { 
    //The inner loop control compares the 0th key value with the next key value, and a maximum number appears each time
    for ($k=0; $k < $length-$i; $k++) { 
      if($arr[$k] > $arr[$k+1]){
        $tmp = $arr[$k+1];
        $arr[$k+1] = $arr[$k];
        $arr[$k] = $tmp;
  return $arr;
  • Select sort

Idea: select one element at a time and put it in the specified position Use the double cycle to complete, the outer layer controls the number of rounds, the current minimum value, and the inner layer controls the number of comparisons

function selectSort($arr){
  //Get length
  $length = count($arr);
  for ($i=0; $i < $length - 1; $i++) { 
    //Location of assumed minimum
    $p = $i;
    //Use the assumed minimum value to compare with other values to find the current minimum value
    for ($j=$i+1; $j < $length; $j++) { 
      //$arr [$p] is the current minimum known
      //Judge the comparison between the current cycle value and the known minimum value, record the key when sending a smaller value, and make the next comparison
      if ($arr[$p] > $arr[$j]) {
        $p = $j; //  Smaller than assumed
    //The key of the current minimum value is found through the internal for loop and saved in $P
    //Judge that the key in the current $p is inconsistent with the key of the assumed minimum value, and increase and exchange it
    if ($p != $i) {
      $tmp = $arr[$p];
      $arr[$p] = $arr[$i];
      $arr[$i] = $tmp;
  //Return the final result
  return $arr;

regular expression

Cache and NoSQL

1. Advantages and disadvantages of redis

1. Excellent reading and writing performance

2. Support data persistenceAOFandRDBTwo persistence methods

3. Master-slave replication is supported. The host will automatically synchronize the data to the slave, which can separate reading and writing.

4. Rich data structure: in addition to supportstringTypevalueAlso supportstringhashsetsortedsetlistAnd other data structures.

1、 RedisWithout automatic fault tolerance and recovery functions, the downtime of the host slave will lead to the failure of some read and write requests in the front end. You need to wait for the machine to restart or manually switch the front endIPTo recover.

2. When the host goes down, some data cannot be synchronized to the slave in time before the shutdown. After switching IP, the problem of data inconsistency will be introduced, which reduces the availability of the system.

3、 redisMaster-slave replication ofFull replication, the host willforkA sub process takes a snapshot of the memory, saves the snapshot of the memory of the sub process as a file and sends it to the slave. This process needs to ensure that the host has enough free memory. If the snapshot file is large, it will have a great impact on the service capacity of the cluster, and the replication process will be carried out when the slave is newly added to the cluster or when the slave is disconnected and reconnected with the host network, that is, network fluctuations will cause a full amount of data replication between the host and the slave, which will cause great trouble to the actual system operation.

4、 RedisIt is difficult to support online capacity expansion. When the cluster capacity reaches the upper limit, online capacity expansion will become very complex. In order to avoid this problem, the operation and maintenance personnel must ensure sufficient space when the system is online, which causes a great waste of resources.

2. Redis application scenario

*Cache – hot data

    • Hotspot data (data that is often queried but not often modified or deleted)
    • Counter

      • Applications such as counting hits. Due to single thread, it can avoid concurrency problems, ensure no errors, and 100% millisecond performance! Don’t forget to persist. After all, redis just saves memory!

    *Command: incrby

    • queue

      • Equivalent to message system. Since redis adds data to the queue to return the number of added elements in the queue, you can judge the number of users accessing this service. Queues can not only turn concurrent requests into serial, but also be used as queues or stacks
    • Distributed lock and single thread mechanism

      • Verify the repeated requests on the front end (you can freely expand similar cases) and filter them through redis: each request stores the request IP, parameter, interface and other hash as a key. Redis (idempotent request) sets how long the validity period is. Then, when the next request comes, first retrieve the key in redis, and then verify whether it is a repeated submission within a certain period of time
      • Second kill system, based on redis, is a single thread feature to prevent database “explosion”
      • Global incremental ID generation, similar to “second kill”
    • Latest list

      • For example, for the latest news list on the news list page, if the total number is large, try not to use the low goods such as select a from a limit 10. Try the lpush command of redis to build the list, and just insert it one by one. But what if the memory is cleared? It’s also simple. If you can’t find the stored key, just use Mysql to query and initialize a list into redis.
    • Ranking List

      • Those who score high rank up. Command: zadd (with sequel, sorted set)

    3. Advantages and disadvantages of mongodb

    1. Transaction operations are not supported
    2. Too much space
    3. Mongodb does not have a mature maintenance tool like mysql
    4. Unable to query the association table, which is not applicable to data with multiple relationships
    5. Complex aggregation operations are created through MapReduce, which is slow
    6. Data errors caused by free and flexible file storage format

    1. The storage method of document structure can obtain data more conveniently
    2. Built in gridfs, supporting high-capacity storage
    3. Built in sharding, easy slicing
    4. Superior performance under massive data
    5. Support for automatic failover (replica set)
    reference resources:…

    The content is collected and sorted for me. If there is any expression error, please correct it