Common PHP Interview Questions

PHP

PHP garbage collection mechanism

PHP can automatically manage memory and clear unnecessary objects.

PHP uses a reference counting GC mechanism.

Each object contains a reference counter refcount, and each reference connected to the object increases the counter by 1. When reference leaves the living space or is set to NULL, the counter is decremented by 1. When an object’s reference counter reaches zero, PHP knows that you no longer need to use the object and releases the memory space it occupies.

Official documentation: https://www.php.net/manual/zh/features.gc.refcounting-basics.php

Difference:

  1. Storage location: Session is stored on the server, and Cookie is stored on the client.
  2. Storage form: Session is stored on the server in the form of an object, and Cookie is stored on the client in the form of a string.
  3. Purpose: Cookies are suitable for saving users’ personal settings, hobbies, etc. Sessions are suitable for customer identity verification.
  4. Path: Sessions cannot distinguish paths. During the same user’s visit to a website, all Sessions can be accessed anywhere. If path parameters are set in cookies, cookies under different paths on the same website cannot access each other.
  5. Security: Cookies are not very safe. Others can analyze the locally stored COOKIE and conduct COOKIE deception. Considering security, session should be used.
  6. Size and quantity limit: The number of cookies contained in each domain name: IE7/8, FireFox: 50, Opera 30; Total cookie size: Firefox and Safari allow cookies up to 4097 bytes, Opera allows cookies up to 4096 bytes, Internet Explorer allows cookies up to 4095 bytes; it is generally believed that Session has no size and quantity limit.

Relationship:

Session requires cookies to work properly. If the client completely disables cookies, the Session will be invalid! Because Session is a server-side storage space maintained by the application server, when the user connects to the server, a unique SessionID will be generated by the server, and the SessionID is used as the identifier to access the server-side Session storage space. The data SessionID is saved to the client and saved with Cookie. When the user submits the page, the SessionID will be submitted to the server to access the Session data. This process does not require developer intervention. So once the client disables Cookie, the Session will also become invalid.

The difference and use of long connections and short connections

Long connection: The client and server first establish a connection. After the connection is established, the connection is not disconnected, and then messages are sent and received. In this way, the communication connection always exists. This method is often used for P2P communication.

Short connection: The client and server only communicate with each other for each message sending and receiving transaction, and the connection is immediately disconnected after the transaction is completed. This method is often used for point-to-multipoint communication. C/S communication.

When to use long connections and short connections: Long connection: Short connections are mostly used for frequent operations, point-to-point communication, and the number of connections cannot be too many. The establishment of each TCP connection requires three handshakes, and the disconnection of each TCP connection requires four handshakes. If you have to establish a connection for each operation and then operate again, the processing speed will be reduced. Therefore, it is enough to directly send data during each operation and the next operation without establishing a TCP connection. For example: long connections are used for database connections. Frequent communication with short connections will cause socket errors. Frequent socket creation is also a waste of resources.

Short connection: HTTP services on web websites generally use short connections. Because long connections consume certain resources for the server. With thousands or even hundreds of millions of client connections like web sites that are so frequent, using short connections can save some resources. Just imagine if long connections are used, and thousands of users are used at the same time, and each user occupies a connection, you can imagine how much pressure the server will have. Therefore, the amount of concurrency is large, but each user needs a short connection if they do not need frequent operations.

http protocol

An HTTP request message consists of four parts: request line, request header, blank line and request data.

Request line

The request line consists of three fields: the request method field, the URL field, and the HTTP protocol version field, which are separated by spaces.

Request header

  • The request header consists of keyword/value pairs, one pair per line, and the keywords and values are separated by English colon “:”.
  • The request header informs the server about the client’s request. Typical request headers are: UserAgent: The browser type that generated the request. Accept: List of content types recognized by the client. Host: The requested host name, allowing multiple domain names to be at the same IP address, that is, a virtual host.

Blank line

The last request header is followed by a blank line, carriage return and line feed characters are sent to notify the server that there are no more request headers below.

Request data

The request data is not used in the GET method, but in the POST method. The POST method is suitable for situations where customers are required to fill out a form. Commonly used request headers related to request data are ContentType and ContentLength.

HTTP response message

The HTTP response also consists of three parts: status line, message response header, and response body.

Status code

1xx: The indication information indicates that the request has been received and processing continues. 2xx: Success indicates that the request has been successfully received, understood, and accepted. 3xx: The redirect requires further action to complete the request. 4xx: Client error The request has a syntax error or the request cannot be fulfilled. 5xx: Server-side error The server failed to fulfill a legitimate request.

Descriptions of common status codes and status descriptions are as follows: 200 OK: The client request was successful. 400 Bad Request: The client request has a syntax error and cannot be understood by the server. 401 Unauthorized: The request is not authorized. This status code must be used with the WWWAuthenticate header field. 403 Forbidden: The server received the request but refused to provide service. 404 Not Found: The requested resource does not exist, for example: the wrong URL was entered. 500 Internal Server Error: An unexpected error occurred on the server. 503 Server Unavailable: The server is currently unable to process the client’s request and may return to normal after a period of time. For example: HTTP/1.1 200 OK (CRLF).

Response header

Informational status code, indicating that everything is normal so far and the client should continue the request. If the request has been completed, it will be ignored. header(‘HTTP/1.1 100 OK’);

//Notify the browser that the page does not exist header(‘HTTP/1.1 404 Not Found’);

//The resource is permanently redirected 301;302: Temporary redirection (the resource is temporarily changed location) header(‘HTTP/1.1 301 Moved Permanently’);

// Jump to a new address header(‘Location: http://php.itcast.cn/’);

// Delayed redirection means jumping every few seconds. header(‘Refresh:10;url=http://php.itcast.cn/’);

//Web page encoding header(‘Content-Type: text/html;charset=utf-8’);

// plain text format header(‘Content-Type:text/plain’);

//JPG, JPEG header(‘Content-Type:image/jpeg’);

//ZIP file header(‘Content-Type:application/zip’);

//PDF file header(‘Content-Type:application/pdf’);

//audio file header(’Content-Type: ’);

//css file header(‘Content-type:text/css’);

Declare a downloaded file header(‘Content-Type:application/octet-stream’); header(‘Content-Disposition:attachment;filename=“ITblog.zip”’);

Displays a login dialog requiring verification header(‘HTTP/1.1 401Unauthorized’); header(‘WWW-Authenticate:Basic realm=“TopSecret”’);

HTTP/2 new features

In 2015, HTTP/2 was released. It is not called HTTP/2.0 because the standards committee does not plan to release any more subversions. The next new version will be HTTP/3.

Binary protocol

The header information of HTTP/1.1 version must be text (ASCII encoding), and the data body can be text or binary. HTTP/2 is a complete binary protocol. The header information and data body are both binary, and are collectively called “frames”: header information frames and data frames.

One benefit of the binary protocol is that additional frames can be defined. HTTP/2 defines nearly ten types of frames, laying the foundation for future advanced applications. If you use text to implement this function, parsing the data will become very troublesome, but binary parsing is much more convenient.

Multiple tasks

HTTP/2 reuses TCP connections. In one connection, both the client and the browser can send multiple requests or responses at the same time without corresponding one-to-one in order, thus avoiding “head-of-line congestion”.

For example, in a TCP connection, the server receives A request and B request at the same time, so it responds to A request first. It turns out that the processing process is very time-consuming, so it sends the processed part of A request, and then responds to B request. After completion, it sends the remaining part of A request.

Such two-way, real-time communication is called multiplexing.

Data flow

Because HTTP/2 data packets are sent out of order, consecutive data packets in the same connection may belong to different responses. Therefore, the packet must be marked to indicate which response it belongs to.

HTTP/2 calls all data packets of each request or response a data stream. Each data stream has a unique number. When a data packet is sent, it must be marked with a data flow ID to distinguish which data flow it belongs to. In addition, it is also stipulated that the ID of the data stream sent by the client is always an odd number, and the ID of the data stream sent by the server is an even number.

When the data stream is sent halfway, both the client and the server can send a signal (RST_STREAM frame) to cancel the data stream. The only way to cancel the data flow in version 1.1 is to close the TCP connection. This means that HTTP/2 can cancel a request while keeping the TCP connection open and available for other requests.

The client can also specify the priority of the data flow. The higher the priority, the sooner the server will respond.

Header information compression

The HTTP protocol is stateless and all information must be attached to each request. Therefore, many fields in the request are repeated, such as Cookie and User Agent. The exact same content must be included in every request, which wastes a lot of bandwidth and also affects the speed.

HTTP/2 has optimized this and introduced header compression. On the one hand, the header information is compressed using gzip or compress before being sent; on the other hand, the client and server maintain a header information table at the same time. All fields will be stored in this table and an index number will be generated. The same fields will not be sent in the future, only the index number will be sent, which improves the speed.

Server Push

HTTP/2 allows the server to actively send resources to the client without request. This is called server push.

A common scenario is that the client requests a web page, which contains many static resources. Under normal circumstances, the client must receive the web page, parse the HTML source code, find static resources, and then issue a static resource request. In fact, the server can expect that after the client requests the web page, it is likely to request static resources again, so it actively sends these static resources to the client along with the web page.

Super global variables

$GLOBALS is a super global variable group of PHP that can be accessed in the entire scope of a PHP script. Is a global combined array containing all variables. The name of the variable is the key of the array. $_SERVER is an array containing information such as header, path, and script locations. The items in this array are created by the web server. There is no guarantee that every server will offer all items; servers may ignore some, or serve items not listed here. $_REQUEST is used to collect data from HTML form submissions. $_POST is widely used to collect form data. Specify this attribute in the HTML form tag: “method=“post”. $_GET is also widely used to collect form data. Specify this attribute in the HTML form tag: “method=“get”. $_COOKIE Variable submitted to the script via the HTTP Cookies method $_SESSION The variable currently registered for the script session. Similar to the old $HTTP_SESSION_VARS array. $_FILES Variable submitted to the script via HTTP POST file upload. Similar to the old $HTTP_POST_FILES array. $_ENV Variables submitted to the script by the execution environment. Similar to the old $HTTP_ENV_VARS array.

MySQL index

What is an index?

An index is a structure that sorts the values of one or more columns in a database table and allows quick access to specific information in a database table. (Excerpted from Baidu Encyclopedia)

Index type

1.FULLTEXT full text index Full-text index, only supported by MyISAM engine. It can be used in CREATE TABLE, ALTER TABLE, and CREATE INDEX, but currently only full-text indexes can be created on CHAR, VARCHAR, and TEXT columns. 2.HASH hash index The uniqueness of the HASH index and the key-value pair-like form are very suitable for use as indexes. The HASH index can be located once and does not need to be referenced layer by layer like a tree index, so it is extremely efficient. But this efficiency is conditional. That is, it is only efficient under the “=” and “in” conditions. For range queries, sorting and combined indexes are still not efficient. 3.BTREE tree index BTREE is a way to store the index into a tree-shaped data structure (binary tree) according to a certain algorithm. Each query starts from the root of the tree entry, traverses the node once, and obtains the leaf. This is the default and most commonly used index type in MySQL. 4.RTREE RTREE is rarely used in MySQL and only supports the geometry data type. The only storage engines that support this storage engine are MyISAM, BDb, InnoDb, NDb, and Archive. Compared with BTREE, the advantage of RTREE lies in range search.

Index type

Normal index: only speeds up queries Unique index: speed up query + unique column value (can have null) Primary key index: speed up query + unique column value (cannot have null) + only one in the table Combined index: Multiple column values form an index, specifically used for combined searches, and its efficiency is greater than index merging Full-text indexing: word segmentation of text content and search Foreign key index: It is connected with the primary key index to ensure the integrity of the data.

Notes on using indexes

  1. Comply with the index and follow the prefix principle
  2. The like query % cannot be forwarded, otherwise the index will become invalid. Use full-text indexing if necessary 3.column is null you can use index
  3. If MySQL estimates that using an index is slower than a full table scan, it will give up using the index.
  4. If there is an index in the condition before or but not in the following condition, the index will not take effect.
  5. The column type is a string. When querying, be sure to add quotes to the value, otherwise the index will be invalid.
  6. Make sure there is only one table column in order by and group by, so that the index can be used

Common high concurrency solutions

Web server optimization: load balancing Traffic optimization: anti-hotlink processing to block malicious requests. Front-end optimization: reduce http requests, add asynchronous requests, enable browser caching and file compression, CDN acceleration, establish an independent image server, Server-side optimization: page staticization, concurrent processing, queue processing, Database optimization: database cache, sub-database and sub-table, partition operation, read-write separation, load balancing