The most grounded set of PHP interview questions (it’s not easy to summarize. I stepped on the pit and hung up a lot of interviews)

Time:2021-10-16

1. Please introduce yourself?

A: I’ll introduce myself. Hello, my name is Liu Mucheng. I’ve been doing PHP development since graduation…

2. What projects are you responsible for in the company?

A: the company’s projects are cross cutting. I have done forums, wechat and shopping malls

3. Why did you come to Shenzhen?

A: people go high

4. What front-end and back-end frames have you used?

A: according to your own answer

5. What modules have you done?

A: login registration, commodity management, shopping cart module, order management

6. What framework does your company use?

A: our company uses the TP framework and uses MySQL + Apache + PHP for development, because the TP framework is a free, open-source, lightweight PHP development framework. It is developed by our Chinese people, and is widely used in China. Various materials are also relatively complete

7. What is MVC? What is the relationship between them?

A: MVC is a development model, which is mainly divided into three parts: m (model), that is, model, which is responsible for data operation; V (view), i.e. view, is responsible for the display of front and background; C (controller), that is, the controller, is responsible for the business logic

The client requests the controller of the project. If data is needed during execution, the controller will obtain data from the model, and then display the obtained data through the view

8. What is OOP?

A: OOP is object-oriented programming. Object-oriented programming is a computer programming architecture. One of the basic principles of OOP is that computer programs are composed of a single unit or object that can play the role of subroutine.

OOP has three characteristics

1. Encapsulation: also known as information hiding, it separates the use and implementation of a class, retains only some interfaces and methods and external connections, or only exposes some methods for developers. Therefore, developers only need to pay attention to how to use this class without paying attention to its specific implementation process. In this way, MVC division of labor and cooperation can be realized, interdependence between programs can be effectively avoided, and loose coupling between code modules can be realized.

2. Inheritance: a subclass automatically inherits the properties and methods in its parent class, and can add new properties and methods or override some properties and methods. Inheritance increases code reusability. PHP only supports single inheritance, that is, a subclass can only have one parent class.

3. Polymorphism: subclasses inherit properties and methods from the parent class and override some of them. Therefore, although multiple subclasses have the same method, the instantiated objects of these subclasses can get completely different results after calling these same methods. This technology is polymorphism. Polymorphism enhances the flexibility of software.

1. Easy maintenance

The structure designed with object-oriented idea has high readability. Due to the existence of inheritance, even if the requirements are changed, the maintenance is only in the local module, so the maintenance is very convenient and low cost.

2. High quality

At design time, existing classes that have been tested in the field of previous projects can be reused to make the system meet business requirements and have high quality.

3. High efficiency

In software development, abstract the real world things according to the needs of design and generate classes. Using this method to solve problems is close to daily life and natural way of thinking, which is bound to improve the efficiency and quality of software development.

4. Easy to expand

Due to the characteristics of inheritance, encapsulation and polymorphism, the system structure with high cohesion and low coupling is naturally designed, which makes the system more flexible, easier to expand and lower cost.

9. What is smart and what is its function?

Answer 1: Smarty is a template engine written in PHP. It is also one of the most famous PHP template engines in the industry

It separates logic code from external display, and provides an easy to manage and use method to separate mixed PHP logic code from HTML code

Answer 2: Smarty is one of the most famous engine frameworks in PHP. Our company uses the TP framework and has encapsulated the Smarty template, so it has not been used alone

Answer 3: Smarty is a template engine. The most obvious thing is that it can cache templates. Generally speaking, the template is to make a static page, then cut some dynamic parts with all separators, then open the template file in PHP, replace the values in the separators, and then output it. You can see the template part in phplib.

After Smarty sets the cache parameters, the template will be opened at the first run time. When PHP replaces the internal values, the read HTML and PHP parts will be regenerated into a temporary PHP file, which eliminates the need to re read the HTML every time it is opened. If you modify the template, just brush it again.

10. What are the advantages of TP framework?

A: TP framework is a framework developed by our Chinese people. Various materials are relatively complete. It is widely used in China. It is relatively simple and convenient, and it is free and open source

11. What are the characteristics of TP?

1. Multi table query is very convenient. You can complete the association operation of multi tables with a few sentences of code in the model

12. Large letter function in TP3 framework?

U: Assembly of URLs

13. Please introduce the laravel framework?

A: the design idea of the laravel framework is relatively advanced, which is very suitable for applying various development modes. As a framework, it has everything ready for you. Composer is the future of PHP. Without composer, PHP is bound to decline

The biggest feature and excellence of laravel framework is that it integrates the relatively new features of PHP, as well as a variety of design patterns, IOC pattern, dependency injection and so on

14. What are the characteristics of laravel?

Answer 1:

1. Powerful rest Router: it can be called with a simple callback function to quickly bind controller and router

Answer 2: the laravel framework introduces facade, dependency injection, IOC pattern, and various design patterns

15. Please briefly describe the database optimization?

A: the database can be optimized from four aspects:

1. Slave structure layer: Web server adopts load balancing server, MySQL server adopts master-slave replication, and read-write separation

16. How to solve exception handling?

A: throw exception: try… Catch is used. The exception code is placed in the try code block. If the exception is not triggered, the code continues to execute. If the exception is triggered, an exception will be thrown. The catch code block catches exceptions and creates an object containing exception information$ E – > getmessage(), output abnormal error information.

Resolve exception: use set_ error_ The handler function gets the exception (you can also use the try () and catch () functions), and then use set_ exception_ The handler () function sets the default exception handler, register_ shutdown_ Function() function. The execution mechanism is that PHP calls the called function into memory, and then calls this function when all PHP statements on the page are completed

17. Front end?

A: I deal with the front-end function in my work. Generally, I use ajax to request data from the background, and then the returned data is displayed in the front page. I have never independently completed HTML and CSS styles by myself. If the company really has such needs, I may find some front-end templates or front-end frameworks, such as h-ui, etc

18. Implementation of rights management (RBAC)?

1. First create a user table: ID name auto (save format: controller method)

2. Then create a base class controller in the background, which encapsulates a construction method. When the user logs in successfully, use the session function encapsulated in the TP framework to obtain the session ID saved in the server, then instantiate the model, obtain the auth data saved in the data table through the user ID, use the expand function to divide the obtained data, and use an array to save it, Then use the constants encapsulated in the TP framework to obtain the current controller and methods, and then assemble them into strings, using in_ The array function determines whether the array contains the currently obtained controller and method. If not, it will prompt that the user has no permission. If so, proceed to the next step

19. Implementation of payment function?

A: it can be implemented step by step according to the API documents of payment. It’s not difficult

20. How to ensure that promotional products will not oversold?

A: this problem was a difficulty in our development at that time. The oversold was mainly caused by the inconsistency between the number of orders placed and the number of products we wanted to promote. Each time, the number of orders was always more than the number of products we promoted. At that time, our group discussed for a long time and gave several schemes to realize it:

The first scheme: before placing an order each time, we judge whether the quantity of promotional goods is enough. If not, we are not allowed to place an order. When changing the inventory, we add a condition to only change the inventory of goods whose inventory is greater than 0. At that time, we used ab for stress test. When the concurrency exceeds 500 and the number of visits exceeds 2000, oversold will still occur. So we denied it.

The second solution: use MySQL transaction and exclusive lock to solve the problem. First, we choose InnoDB as the database storage engine and use exclusive lock to realize it. At the beginning, we tested the shared lock and found that it would still be oversold. One problem is that when we conduct high concurrency testing, it has a great impact on the performance of the database, resulting in great pressure on the database, which is finally denied by us.

The third scheme: using file lock. When a user grabs a promotional product, first trigger the file lock to prevent other users from entering. After the user grabs the promotional product, unlock the file lock and let other users operate. This can solve the problem of oversold, but it will cause great I / O overhead of files.

Finally, we use the redis queue. Store the quantity of products to be promoted in redis in a queue. Whenever a user grabs a promotional product, delete a data from the queue to ensure that the product will not be oversold. This operation is very convenient and efficient. Finally, we adopt this method to realize it

21. The realization of second kill in the mall?

A: Rush buying and second kill are common application scenarios nowadays. There are two main problems to be solved:

1. The pressure of high concurrency on the database

For the first problem, it is easy to think of using cache to deal with rush purchase and avoid directly operating the database, such as redis. The second problem is that we can use the redis queue to complete. We can put the goods to be killed in seconds into the queue. Because pop operations are atomic, even if many users arrive at the same time, they are executed in turn. File locks and transactions are high and the performance drops rapidly. Of course, other aspects should be considered, such as making the rush purchase page static and calling the interface through Ajax, There may also be a situation where a user grabs multiple times. At this time, a queuing queue, purchasing result queue and inventory queue need to be added. In the case of high concurrency, the user is put into the queue, and a thread is used to cycle processing. A user is taken out from the queue to judge whether the user is already in the rush purchase result queue. If so, the user has been rush purchased, otherwise there is no rush purchase, the inventory is reduced by 1, the database is written, and the user is put into the result queue.

22. How does shopping cart work?

A: the shopping cart is equivalent to the shopping cart in the supermarket in reality. The difference is that one is a physical car and the other is a virtual car. Users can jump between different pages of the shopping website to buy their favorite goods. When clicking buy, the goods will be automatically saved to your shopping cart. After repeated purchase, all the selected goods will be placed in the shopping cart and checked out at the checkout counter. This is also to let customers experience the feeling of shopping in real life as much as possible. The server tracks the actions of each user to ensure that each item has its owner when checking out.

It mainly involves the following points:

The key to the implementation of shopping cart is that the server identifies each user and maintains contact with them. However, HTTP protocol is a “stateless” protocol, so the server can’t remember who is buying goods. When adding goods to the shopping cart, the server doesn’t know what was in the shopping cart, so that the shopping cart can’t be “carried around” when users jump between different pages, which makes it difficult to realize the shopping cart.

At present, the implementation of shopping cart is mainly through cookie, session or combined with database. Let’s analyze their mechanism and function.

cookie

A cookie is a piece of information generated by the server and stored on the client. It defines a mechanism for the web server to store and return information on the client. Cookie files contain domain, path, lifetime, and variable values set by the server. When a user accesses the same web server in the future, the browser will send the cookie to the server as it is. By allowing the server to read the information originally saved to the client, the website can provide a series of conveniences for visitors, such as identifying the user’s identity in the process of online transactions, avoiding users from repeatedly entering names and passwords in situations with low security requirements, customizing the home page of the portal website, targeted advertising, etc. Using the characteristics of cookies greatly expands the functions of web applications. It can not only establish the connection between the server and the client, because cookies can be customized by the server, but also store the cookie value generated by shopping information in the client, so as to realize the function of shopping cart. Using cookie based method to realize the session or shopping cart between server and browser has the following characteristics:

1. Cookies are stored on the client and take up very little resources. The browser allows 300 cookies, and the size of each cookie is 4KB, which is enough to meet the requirements of the shopping cart and reduce the load of the server;

session

Session is another way to implement shopping cart. Session provides the function of saving and tracking the user’s state information, so that the variables and objects defined by the current user in the session can be shared between pages, but can not be accessed by other users in the application. The most important difference between session and cookie is that session stores the user’s private information on the server during the session, which improves the security. After the server generates a session, the client will generate a sessionid and save the identification number in the client to maintain synchronization with the server. This sessionid is read-only. If the client prohibits the cookie function, the session will be transmitted between pages by attaching parameters to the URL or submitting implicitly in the form. Therefore, using session to manage users is more safe and effective.

Similarly, the shopping cart can also be realized by using session. The characteristics of this method are as follows:

1. Session uses a new mechanism to keep synchronization with the client, which does not depend on the client settings;

Combined with database

This is also a common mode at present. In this way, the database is used to store shopping information, and session or cookie is used to track users. This method has the following characteristics:

1. Database and cookie are respectively responsible for recording data and maintaining session, which can give full play to their respective advantages and improve the security and server performance;

Selection of various methods:

Although a cookie can be used to implement a shopping cart, it must be supported by the browser. In addition, it is the information stored on the client, which is very easy to obtain, so it also restricts it from storing more and more important information. Therefore, cookies are generally only used to maintain the session with the server. For example, the largest Dangdang online bookstore in China uses cookies to keep in touch with customers, but the biggest disadvantage of this method is that if the client does not support cookies, the shopping cart will become invalid.

Session can maintain a good session with both parties of the transaction, and the settings of the client can be ignored. It has been widely used in shopping cart technology. However, the file attribute of session still leaves a security risk.

Although the method of combining with the database solves the above problems to a certain extent, it can be seen from the above example that the frequent operation of the database table is involved in this shopping process. In particular, users have to connect with the database every time they buy goods. When there are many users, it increases the load of the server and database.

23. What should I pay attention to when redis message queue is FIFO?

A: a list is usually used to implement queue operations, which has a small limitation. Therefore, all tasks are first in first out. If you want to give priority to a task, it is not easy to deal with it. This requires the concept of queue priority. We can give priority to high-level tasks in the following ways:

1) Single list implementation: the normal operation of the queue is left in right out (lpush, rpop). In order to process high priority tasks first, when encountering high-level tasks, you can directly jump in the queue and put them directly into the queue head (rpush). In this way, when you get tasks from the queue head (right), you get high priority tasks (rpop)

2) Two queues, one ordinary queue and one advanced queue, are used. They are placed in different queues according to the level of the task. It is also very simple to obtain the task. The brpop command of redis can take values from multiple queues in order. Brpop will be viewed according to the given key order, and an element will pop up at the end of the first non empty list found. Redis > brpop LIST1 List2 0

LIST1 as a high priority task queue

24. What are the challenges of the module you are responsible for?

A: in the B2B e-commerce project I was responsible for, I was responsible for the order module at that time. Because the customer selected the goods of multiple merchants at one time, and finally generated an order, our platform did not know which merchant the fee should be paid to when settling the merchant. At this time, our group discussed that the order splitting needs to be involved, that is, after the user clicks payment, If there are multiple goods and they are not in the same store, order splitting is required. For example, if there are two goods and they are not in the same store, generate two sub order numbers under the original order number and modify the order numbers of the two goods in the order table. Finally, we realized the distribution management of goods and solved our problems.

I think there are only two problems encountered in the development process. One is at the technical level. I think as long as you have perseverance and enthusiasm, there are no problems you can’t think of. The other is communication. Communication is the most important everywhere and at any time, especially when we do development. If we don’t communicate well, it will affect the progress of the whole project. I am a very good communicator, so I don’t have much problem in this regard.

25. How do users handle their orders?

A: judge whether the user has logged in. If he has not logged in, he is not allowed to place an order. After logging in, you can place an order and generate a unique order number. At this time, the status of the order is unpaid.

26. How is e-commerce login realized?

A: it is divided into ordinary login and third-party login. The third-party login mainly uses the author protocol. I will take the third-party login of QQ as an example: when the user requests the third-party login of QQ on our site, our site will guide the user to jump to the login authorization interface of QQ, When the user enters QQ and password and successfully logs in, it will automatically jump back to the callback page set by our site with a code parameter. Then you can use code to request the authorization page of QQ again, and you can get an access token from it_ Token, we can call the interface provided by QQ, such as getting open_ ID, you can get the basic information of the user. After obtaining it, we need to get the user’s authorization information and open_ ID is bound to ordinary users of our platform. In this way, both ordinary users and third-party users can log in.

27. How is the interface security handled?

A: we did this at that time. We used the HTTP post method to digitally sign the fixed parameters + additional parameters, using MD5 encryption. For example, I want to obtain a message through the title, use the information title + date + a key agreed by both parties on the client, generate a signature through MD5 encryption, and then pass it to the server as a parameter, The server uses the same method for verification. If the received sign is the same as the value calculated by our algorithm, it is proved that it is a normal interface request, and we will return the corresponding interface data.

28. What technology is used to send SMS and where to call it?

A: I mainly use the third-party SMS interface to configure the corresponding information when applying for the interface, and then call it where SMS verification is needed on our site. We usually use it when users register.

29. What difficulties do you encounter in your work?

A: Generally speaking, I mainly encounter these difficult problems in my work:

① When I was working before, I found that some temporary needs often disrupted my plan, so that sometimes this task has not been completed, and I have to do other tasks. At the end of the last day, there are many large and small things, but they have not been completed very well. I will add these priorities and meet temporary needs, Rearrange the existing tasks and temporary tasks according to the priority to ensure the efficient completion of tasks with high priority within the specified time.

② When meeting the needs of the project, people with poor understanding are easy to be angry and affect their emotions during communication. In the end, they can’t achieve the desired effect. Later, every time I come to this kind of time, I usually use some paper and more image things to communicate in a way that both sides agree and understand, which reduces a lot of unnecessary trouble. As we all know, changing requirements is a very painful thing for programmers, so early communication is very important.

③ Another thing, my former leaders didn’t know much about technology, so every time a new demand came out, they always asked us to complete it in a very short time. If we couldn’t finish it, we would be suspected of having a problem with our ability. Of course, every leader wants his employees to complete the task as soon as possible, reduce costs and improve efficiency. At this time, I will refine our requirements, list the key points and difficulties, make time planning, patiently communicate with leaders, the importance of each point of the project and the proportion of time spent, so as to ensure that the tasks can be completed with quality and quantity within this planned time point. Slowly, it has also been recognized by the leaders. In fact, the leaders are not unreasonable. As long as they plan things and exchange the lowest price for the highest value, everyone can easily understand it

30. How can users directly join the shopping cart without logging in?

A: without logging in, the user can save the information of the commodity to be purchased (such as commodity ID, commodity price, sku_id of commodity, purchase quantity and other key data) into cookie. When logging in. Save the contents of cookie to the database and clear the data in the cookie.

31. Have you written an interface and how to define it?

A: Yes. There are two kinds of interfaces: one is data interface and the other is application interface.

Data interface: it is a “structure” more abstract than an abstract class – it is not a class, but a syntax structure like a class. It is a structural specification that specifies the format in which our class should be defined. It is generally used when the team is large and there are many branches.

Application interfaceAPI (application interface): an entry for external data access

I am mainly involved in the preparation of the interface in app development. We will provide them with corresponding data according to what data the client needs. The data is returned in JSON / XML format and equipped with corresponding interface documents.

32. SKU inventory reduction?

Answer: SKU = stock keeping unit

That is, the unit of inventory in / out measurement, which can be piece, box, pallet, etc. SKU is the inventory unit, which distinguishes between single items.

It is most widely used in clothing and footwear. For example, a SKU in a textile usually represents: specification, color and style.

When designing a table, there is not only a commodity table, but also a total inventory in the commodity table. We also need to involve a SKU table with SKU inventory and unit price fields. Every time you buy a commodity, you actually buy SKU commodities. In this way, after placing an order successfully, you should reduce the corresponding SKU inventory according to the unique SKU number of the purchased commodity, Of course, the total inventory of goods is saved in the goods master table, and the inventory in the total inventory also needs to be reduced.

33. Inventory settings?

A: inventory is divided into total commodity inventory and SKU inventory. Often, the total commodity inventory is the sum of SKU inventory. Generally, after the maximum inventory and minimum inventory are set for goods in the background of the mall, the current inventory quantity is compared with the maximum and minimum. If it exceeds or is lower than the inventory, it will be counted and reflected in the form of a report, which is convenient for users to master the status and quantity of goods in excess and shortage.

34. How to ensure data consistency between order and inventory tables?

A: in an e-commerce system, it is normal to reduce the corresponding inventory after the order is successfully generated. The consistency between the two must be ensured. However, sometimes the order is successful but the inventory is not reduced due to some reasons, such as program logic problems, concurrency and so on. This is not allowed. Transactions in MySQL can solve this problem. First, we have to select InnoDB as the storage engine of the database. The transaction stipulates that transactions can be submitted only after the order is completed and the corresponding inventory is reduced. Otherwise, the transaction will be rolled back to ensure data consistency.

35. How to ensure the consistency of Ba end data when o2o users place orders and C-end orders?

A: o2o is an online and offline mode. O2o mode pursues the consumption mode of “online payment + physical store consumption”, that is, after consumers place an online order and complete the payment, they will consume in the physical store with the consumption voucher. O2o mode puts merchant information and payment procedures online, while cashing goods and services offline, that is, o2o mode is applicable to tangible products that cannot be delivered by express. The problem of data consistency is the most common problem in o2o industry. We can solve this problem similar to the idea of master-slave replication of database. O2o has a supplier system, which is similar to the master server. When placing an order at the ç end (slave server), the data is synchronously updated to the supplier system. B and a pull data from the supplier system in real time for synchronization, For example, use the scheduled task to pull data regularly for synchronization.

36. How does redis prevent high concurrency?

A: in fact, redis will not have concurrency problems, because it is a single process, and no matter how many commands are executed one by one. When we use, there may be concurrency problems, such as obtaining and setting this pair. Why does redis have high concurrency problems? Redis’s birth decision

Redis is a NoSQL database with single thread mechanism. Based on key value, the data can be persistent and dropped. Because of the single thread, redis itself does not have the concept of lock, and there is no competition between multiple client connections, but there will be problems when using jedis and other clients to access redis concurrently. Connection timeout, data conversion error, blocking, client closing connection and other problems occur. These problems are caused by client connection confusion.

At the same time, the nature of single thread determines that operations on the same key with high concurrency will be queued. If the concurrency is large, it may cause subsequent request timeout.

When accessing redis remotely, there is a problem of high concurrent access delay due to network and other reasons.

terms of settlement

The connection is pooled at the client, and the client read-write redis operation is synchronized with the internal lock.

From the perspective of server, setnx redirection is used to realize the locking mechanism.

37. How did you get the details of the second kill?

A: pass the performance test and simulate the second kill scenario. Each problem has been repeatedly tested, constantly found and solved.

38. What database is used for second kill and how is it realized?

A: because at the moment of second kill, the concurrency is very large. If you request the database at the same time, it will lead to great pressure on the database, resulting in a sharp decline in the performance of the database, and more seriously, it may lead to the downtime of the database server. At this time, the memory cache database redis is generally used. Redis is a non relational database and redis is a single thread. The second kill process can be completed through the redis queue.

39. how did the Alipay process come true?

Answer: first, we must have a Alipay account, then apply to Alipay for online payment business and sign the agreement. After the agreement comes into effect, the Alipay side will give the website partner a ID and a security check code. With these two things, you can develop the Alipay interface according to the Alipay interface document, and the middle is mainly related to a security problem. The whole process is like this: our website passes the corresponding parameters (such as the total amount of order, order number) to the payment page through post, the payment page processes a series of parameters, submits it to Alipay server in post mode, Alipay server validates, and processes the received data. Return the processed results to the asynchronous and synchronous callback addresses set on our website, and process the corresponding business logic through the corresponding return parameters. For example, the returned parameters represent successful payment and change the order status.

40. What is single sign on?

A: single sign on (SSO) is simple. In an environment where multiple systems coexist, users do not have to log in to other systems after logging in at one place, that is, users can be trusted by all other systems at one time.

41. Under what circumstances is caching used?

A: when users access the application system for the first time, they will be guided to the authentication system to log in because they have not logged in yet; According to the login information provided by the user, the authentication system performs identity verification. If it passes the verification, it should return an authentication credential – ticket to the user; When users visit other applications, they will bring this ticket as their authentication credentials. After receiving the request, the application system will send the ticket to the authentication system for verification and check the legitimacy of the ticket. If the verification is passed, the user can access application system 2 and application system 3 without logging in again.

Main technical points:

42. How to realize third-party login?

A: the third-party login is mainly implemented based on the author protocol. The implementation process is briefly described below:

1. First, we need to apply to the third-party login platform as a developer to access the application. After the application is successful, we will get an appid and a secrectid

43. How to handle load and high concurrency? (take a good look, often ask, can answer the main things)?

A: from the perspective of low cost, high performance and high expansibility, there are the following treatment schemes:

1. HTML static

In fact, as we all know, the most efficient and least expensive is the pure static HTML page, so we try our best to make the pages on our website use static pages. This simplest method is actually the most effective method.

2. Picture server separation

Store the pictures separately to minimize the overhead of large traffic such as pictures. You can put them on some related platforms, such as riding cattle

3. Database cluster and database table hashing and caching

The concurrent connection of the database is 100. One database is far from enough. We can start from the aspects of read-write separation, master-slave replication and database cluster. In addition, to minimize database access, cache databases such as Memcache and redis can be used.

4. Mirror image:

Download can be minimized, and different requests can be distributed to multiple image ends.

5. Load balancing:

The maximum concurrent connection of Apache is 1500. You can only add servers. You can start with hardware, such as F5 server. Of course, the cost of hardware is relatively high, and we often start with software.

Load balancing is based on the existing network structure. It provides a cheap, effective and transparent method to expand the bandwidth of network equipment and servers, increase throughput, strengthen network data processing capacity, and improve the flexibility and availability of the network. At present, the most widely used load balancing software are nginx, LVS and haproxy. Let me talk about the advantages and disadvantages of the following three:

The advantages of nginx are:

Working on layer 7 of the network, you can do some diversion strategies for HTTP applications. For example, for domain names and directory structures, its regular rules are more powerful and flexible than haproxy, which is one of the main reasons why it is widely popular at present. Nginx alone has far more fields to use than LVS.

Nginx has very little dependence on network stability. Theoretically, it can perform load function if it can ping. This is also one of its advantages; On the contrary, LVS relies heavily on network stability, which I deeply understand;

Nginx is easy to install and configure and easy to test. It can basically print out errors with logs. The configuration and testing of LVS will take a long time, and LVS relies heavily on the network.

It can bear high load pressure and is stable. When the hardware is not poor, it can generally support tens of thousands of concurrent times, and the load degree is relatively smaller than LVS.

Nginx can detect the internal faults of the server through the port, such as the status code and timeout returned by the server processing the web page, and resubmit the request that returns an error to another node, but the disadvantage is that it does not support URL detection. For example, if the user is uploading a file, and the node processing the upload happens to fail during the upload process, nginx will switch the upload to another server for reprocessing, and the LVS will be directly disconnected. If you upload a large file or a very important file, the user may be dissatisfied with it.

Nginx is not only an excellent load balancer / reverse proxy software, but also a powerful web application server. LNMP is also a very popular web architecture in recent years, and it has good stability in high traffic environment.

Nginx is becoming more and more mature as a web reverse acceleration cache, which is faster than the traditional squid server. You can consider using it as a reverse proxy accelerator.

Nginx can be used as a middle-level reverse agent. At this level, nginx basically has no opponent. The only thing that can compare with nginx is lighttpd. However, lighttpd has not achieved the complete function of nginx, the configuration is not so clear and easy to read, and the community data is far less active than nginx.

Nginx can also be used as a static web page and image server, and its performance is unmatched. In addition, the nginx community is very active and there are many third-party modules.

The disadvantages of nginx are:

Nginx can only support HTTP, HTTPS and email protocols, which makes it less applicable. This is its disadvantage.

The health check of the back-end server only supports the detection through the port, not through the URL. The direct holding of session is not supported, but it can be through IP_ Hash to solve.

LVS: use Linux kernel cluster to realize a high-performance and highly available load balancing server, which has good scalability, reliability and manageability.

The advantages of LVS are:

It has strong load resistance. It works on the four layers of the network, only for distribution, and there is no traffic. This feature also determines that it has the strongest performance in the load balancing software, and the consumption of memory and CPU resources is relatively low.

Low configurability is not only a disadvantage but also an advantage. There are not many things that can be configured, so there is no need for too much contact, which greatly reduces the probability of human error.

It works stably because it has strong load resistance and has a complete dual machine hot standby scheme, such as LVS + kept. However, LVS / DR + kept is the most used in the project implementation.

There is no traffic. LVS only distributes requests, and the traffic does not go out from itself, which ensures that the performance of equalizer IO will not be affected by large traffic.

It has a wide range of applications. Because LVS works on layer 4, it can load balance almost all applications, including HTTP, database, online chat room and so on.

The disadvantages of LVS are:

The software itself does not support regular expression processing and can not do dynamic and static separation; Now many websites have strong demand in this regard, which is the advantage of nginx / haproxy + kept.

If the website application is relatively large, the implementation of LVS / DR + kept will be more complex, especially if there are windows server machines behind it. If the implementation, configuration and maintenance process are more complex, nginx / haproxy + kept will be much simpler.

Haproxy features:

Haproxy also supports virtual hosts.

The advantages of haproxy can supplement some shortcomings of nginx, such as supporting session retention and cookie guidance; It also supports detecting the status of the back-end server by obtaining the specified URL.

Haproxy is similar to LVS. It is just a load balancing software; In terms of efficiency, haproxy has better load balancing speed than nginx, and is also better than nginx in concurrent processing.

Haproxy supports load balancing forwarding of TCP protocol. It can load balance MySQL reads, detect and load balance MySQL nodes at the back end. You can use LVS + kept to load balance MySQL master-slave.

There are many load balancing strategies for haproxy. There are 8 specific load balancing algorithms for haproxy:

① Roundrobin means simple polling. It’s not much to say. It’s basically available for load balancing;

② Static RR indicates that attention is recommended according to the weight;

③ Leastconn, which means that the least connected person handles it first, and it is recommended to pay attention to it;

④ Source indicates the IP address of the request source, which is the same as that of nginx_ The hash mechanism is similar. We use it as a method to solve the session problem and suggest paying attention to it;

⑤ RI, indicating the URI according to the request;

⑥ rl_ Param, indicating the ‘balance URL’ according to the URL parameter of the request_ param’ requires an URL parameter name;

⑦ HDR (name), which means that each HTTP request is locked according to the HTTP request header;

⑧ RDP cookie (name) means that each TCP request is locked and hashed according to the cookie (name).

Summary of comparison between nginx and LVS:

Nginx works in layer 7 of the network, so it can make diversion strategies for HTTP applications, such as domain names, directory structures, etc. in contrast, LVS does not have such functions, so nginx can use more occasions than LVS alone; However, these useful functions of nginx make it more adjustable than LVS, so you often have to touch it. If you touch more, you will have a greater chance of human problems.

Nginx relies less on network stability. In theory, as long as Ping is successful and web page access is normal, nginx can be connected. This is a major advantage of nginx! Nginx can also distinguish between internal and external networks. If a node has both internal and external networks, it is equivalent to that a single machine has a backup line; LVS depends on the network environment. At present, the server is in the same network segment, and LVS uses direct shunting to ensure the effect. In addition, it should be noted that LVS needs to apply to the hosting provider for at least one more IP to do visual IP. It seems that it can’t use its own IP to do VIP. To be a good LVS administrator, you really have to follow up and learn a lot of knowledge about network communication, which is no longer as simple as HTTP.

Nginx is easy to install and configure and easy to test, because it can basically print out errors with logs. The installation, configuration and testing of LVS will take a long time; LVS relies heavily on the network. Most of the time, it cannot be configured successfully because of network problems rather than configuration problems. It will be much more troublesome to solve problems.

Nginx can also bear high load and is stable, but the load and stability are poor. LVS has several levels: nginx handles all traffic, so it is limited by machine IO and configuration; Its own bugs are still unavoidable.

Nginx can detect the internal faults of the server, such as the status code and timeout returned by the server processing the web page, and resubmit the request that returns an error to another node. At present, ldirectd in LVS can also support monitoring for the internal situation of the server, but the principle of LVS makes it impossible to resend requests. For example, if the user is uploading a file, and the node processing the upload happens to fail during the upload process, nginx will switch the upload to another server for reprocessing, and the LVS will be directly disconnected. If you upload a large file or a very important file, the user may be annoyed.

The asynchronous processing of requests by nginx can help the node server reduce the load. If Apache is used for direct external services, the Apache server will occupy a lot of memory and cannot release many narrow-band links. If one more nginx is used as the Apache agent, these narrow-band links will be blocked by nginx and there will be no excessive requests on Apache, This reduces a considerable amount of resource occupation. In this regard, using squid has the same effect. Even if squid itself is configured not to cache, it is still very helpful to Apache.

Nginx can support HTTP, HTTPS and email (email functions are rarely used), and LVS supports more applications than nginx. In terms of use, the most front-end strategy should be LVS, that is, the direction of DNS should be LVS equalizer. The advantages of LVS make it very suitable for this task. Important IP addresses are best managed by LVS, such as database IP, WebService server IP, etc. These IP addresses will be used more and more over time. If the IP is replaced, faults will follow. Therefore, it is most secure to entrust these important IP addresses to LVS hosting. The only disadvantage of this is that there will be a large number of VIPs. Nginx can be used as an LVS node machine. First, it can take advantage of the functions of nginx, and second, it can take advantage of the performance of nginx. Of course, squid can also be used directly at this level. Squid’s function is much weaker than nginx, and its performance is also inferior to nginx. Nginx can also be used as a middle-level agent. At this level, nginx basically has no opponent. The only thing that can shake nginx is lighttpd. However, lighttpd has not yet achieved the complete function of nginx, and the configuration is not so clear and easy to read. In addition, the IP of the middle-level agent is also important, so the middle-level agent also has a VIP and LVS, which is the most perfect solution. Specific applications need to be analyzed in detail. If it is a relatively small website (daily PV is less than 10 million), nginx can be used. If there are many machines, DNS polling can be used, and LVS still consumes more machines; For large websites or important services, when the machine is not worried, we should consider using LVS more.

Database optimization

44. Did you consider locking the watch when doing the second kill?

A: Yes, we considered several solutions when we did the second kill. One of them was to use transaction and exclusive lock.

45. Have you ever touched architecture?

Yes, I have. I have configured it on my own server. I have done the following configuration and testing of architecture before;

1. Database read-write separation, master-slave replication and clustering.

46. Encapsulated in a simple framework?

Answer; It encapsulates a simple MVC framework, which is mainly divided into three layers, controller layer and model layer, view layer, route allocation and entry file, template engine, singleton mode, factory mode, introduction of third-party class library, etc.

47. Talk about your understanding of MVC?

A: the core idea is that the view and user interaction cause the controller to change through events. The controller change causes the model to change or the controller changes both at the same time. The model change causes the view to change or the view changes. It is possible to obtain parameters from the model to change itself. Its advantage is that it can separate the interface from the business logic.

Model is the main part of the program, mainly including business data and business logic. In the model layer, it also involves the services published by users. In the service, the data in the business model will be updated according to different business requirements.

48. What is the difference between session and cookie?

1. The cookie data is stored on the browser of the third-party application, and the session data is placed on the server.

49.echo(),print(),print_ What’s the difference between R?

Echo can output multiple values at a time, separated by commas. Echo is a language structure, not a real function, so it cannot be used as part of an expression. Echo is an internal instruction of PHP, not a function, and has no return value.

50. Say single or double quotation marks?

① Variables inside single quotation marks are not executed, and double quotation marks are executed

51. Advantages and disadvantages of index?

1. Advantages:

a) It can ensure the uniqueness of the data of each row in the database table

2. Disadvantages:

a) Creating and maintaining indexes takes time, which increases with the amount of data

52. What is the difference between get and post?

1 \. Get is to get data from the server, and post is to transfer data to the server.

53. How to modify the lifetime of a session?

1: Set session.gc in php.ini_ Maxlifetime = 1440 / / default time

54. Linux basic commands, directory structure?

Arch displays the processor architecture of the machine

55. What data does Memcache cache cache?

1、 Data that is often read and does not have strong real-time requirements can wait until it expires automatically. For example, the latest article list on the home page of the website, so and so ranking and other data.

56. Magic method, magic constant?

1 __ construct()

Magic constant:

__ LINE__

57. What is the difference between an interface and an abstract class?

A: an abstract class is a class that cannot be instantiated and can only be used as a parent of other classes. Abstract classes are declared with the keyword abstract.

Abstract classes are similar to ordinary classes and contain member variables and member methods. The difference between the two is that the abstract class must contain at least one abstract method. The abstract method has no method body, and the method is naturally rewritten by subclasses.

The format of the abstract method is: abstract function abstractmethod();

The interface is declared through the interface keyword. The member constants and methods in the interface are public. Methods can not write the keyword public. Methods in the interface also have no method body. The methods in the interface are naturally implemented by subclasses.

The functions of abstract classes and interfaces are very similar. The biggest difference is that interfaces can implement multiple inheritance. Whether you choose an abstract class or an interface in an application depends on the specific implementation.

Subclasses inherit, abstract classes use extensions, and subclass implementation interfaces use implements.

58. What is a queue? Exclusive lock, how to solve MyISAM deadlock?

A: by default, MyISAM is a table level lock, so multiple actions of operating a single table at the same time can only be performed in the form of queue;

Exclusive locks, also known as write locks, are written to exclude other requests during SQL execution and will be automatically released after execution;

Deadlock resolution: first find the deadlock thread number, and then kill the thread ID

59. What are the advantages of bootstrap framework?

A: bootstrap is a web development framework. It is composed of CSS, JavaScript and HTML. It is simple and flexible, making web development faster

advantage:

① Save time: using the bootstrap framework can greatly save project development time. It contains a lot of ready-made code. If you need to use it, you only need to find the appropriate code and insert it into the appropriate location. In addition, CSS is written by less, and many styles and designs have been designed

② Customization: bootstrap can retain the required parts of the framework according to its own projects

③ Reasonable design:

Grid system: bootstrap defines 12 grid system. When the page has been completed, you can change the number of lines and layout size according to your own needs according to the appropriate grid. The style has been developed. You only need to put the code into the appropriate HTML code location

Less: less is a high-level language based on CSS. Its purpose is to make CSS development more flexible and powerful

Javascript: bootstrap provides a JavaScript library that goes beyond the basic architecture and style. Developers can easily operate the window, warning box, tooltip box, etc., which can avoid our trouble in writing scripts

4. Consistency: bootstrap can ensure the unity of the interface on different platforms, such as ie, chrome, etc

5. Continuous update: bootstrap is constantly improving, more regular and continuous

6. Responsive: the consistency of the interface can be maintained both at the PC end and the mobile end

7. Many documents: there are many bootstraps

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Talk and laugh with Hongru, no baiding!