Summary of the interview questions of the latest PHP senior engineers in large factories in 2020 (1)

Time:2021-3-5

1. Give you four coordinate points to judge whether they can form a rectangle. For example, judge whether ([0,0], [0,1], [1,1], [1,0]) can form a rectangle.

Let’s analyze the problem and give 4 punctuation points to judge whether it is rectangular or not

High school knowledge, rectangle has four sides, two equal, rectangular two diagonal equal, rectangular long and short sides and diagonal meet the Pythagorean theorem.

So the solution is that according to the coordinate points,

List all the arrays of the lengths of the two-point combination sides, remove the duplicate, and see if there are only three lengths left (note the two lengths of the square)

Judge whether the Pythagorean theorem is satisfied or not

Tune it. First, judge whether there are duplicate points. If there are some, they are definitely not rectangles

The code is as follows:

2. Write a piece of code to judge whether a ring is formed in the one-way linked list. If a ring is formed, please find out the entrance of the ring, that is, point P

/*
 *Node class of single linked list
 */
class LNode{
    //In order to simplify the access to the single linked table, the access permission of the data items in the node is set to public
    public int data;
    public LNode next;
}

class LinkListUtli {
    //Null is returned when there is no ring in the single linked list, and the entry node of the ring is returned when there is a ring
    public static LNode searchEntranceNode(LNode L)
    {
        Lnode slow = L; // P is the pointer that starts from the beginning node and goes back one step at a time
        Lnode fast = L; // Q is the pointer that starts from the beginning node and goes back two steps at a time
        while(fast !=null && fast.next !=null) 
        {
            If (slow = = fast) break; // P is equal to Q, the single linked list has rings
            slow=slow.next;
            fast=fast.next.next;
        }
        if(fast==null || fast.next==null) return null;

        //Traverse again to find the entry point of the ring
        slow=L;
        while(slow!=fast)
        {
            slow=slow.next;
            fast=fast.next;
        }

        return slow;
    }
}

3. Write a function to get all the pictures in an article and download them

function download_images($article_url = '', $image_path = 'tmp'){

    //Get article class content
    $content = file_get_contents($article_url);

    //Using regular expression to get picture link
    $reg_tag = '//';
    $ret = preg_match_all($reg_tag, $content, $match_result); 
    $pic_url_array = array_unique($match_result1[1]);

    //Create path
    $dir = getcwd() . DIRECTORY_SEPARATOR .$image_path;
    mkdir(iconv("UTF-8", "GBK", $dir), 0777, true);

    foreach($pic_url_array as $pic_url){
        //Get file information
        $ch = curl_init($pic_url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE );
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $fileInfo = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);

        //Get image file suffix
        $ext = strrchr($pic_url, '.');
        $filename = $dir . '/' . uniqid() . $ext; 

        //Save picture information to file
        $local_file = fopen($filename, 'w');
        if(false !== $local_file){
            if( false !== fwrite($local_file, $filecontent) ){
            fclose($local_file);
            }
        }
    }

}

4. Obtain the IP address of the current client and judge whether it is in (111.111.111.111222.222.222)

If you are not using a proxy server:

$ip = $_SERVER[‘REMOTE_ADDR’];

Use transparent proxy

$ip = $_SERVER[‘HTTP_X_FORWARDED_FOR’];

5. Log of nginx_ The format configuration is as follows:

log_format main ‘remoteaddr−remote_user [timelocal]"request”’ 
‘statusbody_bytes_sent “httpreferer"″"http_user_agent” “upstreamresponsetime""request_time” “http_x_forwarded_for"';

From today’s nginx log file access.log Medium:

  • a. List “request”_ The largest 20 lines of “time”?
  • b. List 20 URL addresses with long traffic at 10 a.m?

6. What is CSRF attack? XSS attack? How to prevent it?

CSRF: Cross Site Request Forgery can be prevented by judging the source and adding token.

XSS: cross site scripting attack, which can be prevented by content escape and filtering, and CSP

7. In the application, we often encounter the situation of randomly fetching 10 pieces of data in the user table to display. Briefly describe how you realize this function.

SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;

8. Randomly draw 5 cards from playing cards to judge whether it is a Shun Zi, that is, the 5 cards are continuous

There is a key point to this problem, playing cards, 1-13 can not be more. It’s very simple. Do it with PHP, define an array to store 1 to 13 respectively, take one out, empty one, and finally see if the five empty ones are continuous. In this case, the order of extraction is not considered.

9. How to find the first common node of two intersecting one-way linked lists

Thought:

  1. If two linked lists intersect, the following nodes are the same from the intersection point, that is, the last node must be the same;
  2. Traverse two linked lists from the beginning to the end, and record the length of the linked list. When the tail nodes of the two are different, they must not intersect;
  3. If the length of a is La and B is lb, if LA > lb, the first la-lb of a is skipped first

If two one-way linked lists have a common node, that is to say, if two linked lists start from a node, their M_ Pnext points to the same node. But because it is a node of one-way linked list, each node has only one M_ Therefore, starting from the first common node, all the nodes are coincident, and there is no possibility of bifurcation. Therefore, the topological shape of two partially overlapped linked lists with common nodes looks like a Y instead of an X.

10. For the longest common subsequence problem LCS, if there are two arrays [1,2,5,11,32,15,77] and [99,32,15,5,1,77], find the number they have in common, and write the code with the best time complexity. Array cannot be used_ Intersect (there are pits here. We need to study dynamic programming).

11. The principle of memory allocation and multithreading in Linux

12. The difference between primary key and unique index in MySQL

Primary key: must not have empty value. Unique index: can have null value

13. Main differences between HTTP and HTTPS

The key is s. In short, after establishing a connection with HTTPS, you need to send the SSL certificate first. With the public key and private key, you can decrypt it.

14. HTTP status code and its meaning

  • 200 the request is successful, and the response header or data body expected by the request will be returned with the response.
  • 301 the requested resource has been permanently moved to a new location.
  • 302 the requested resource now temporarily responds to the request from a different URI.
  • 400 1. Semantic error. The current request cannot be understood by the server. 2. Wrong request parameter.
  • 401 the current request requires user authentication.
  • 403 the server understood the request, but refused to execute it.
  • 404 the request failed. The desired resource was not found on the server.
  • 500 server encountered an unexpected situation, unable to complete the processing of the request, will appear when the code error.
  • 501 server does not support a function required by the current request. The requested method is not recognized.
  • 502 when a server working as a gateway or proxy attempts to execute a request, an invalid response is received from the upstream server.
  • 503 due to temporary server maintenance or overload, the server is currently unable to process the request.

15. How to check the system resource occupancy in Linux

top、htop、free、uptime

16. What is the principle of SQL injection? How to prevent SQL injection

Principle: first, there is a problem with SQL itself (this is not the main problem). Second, the SQL you write is very problematic (this is the most important)

Prevention: first, never trust anything the user enters. Second, precompile. Now the framework will generally have SQL filtering.

17. Isset (null) isset (false) empty (null) empty (false) output

PHP entry problem, the difference between isset and empty

They are false, true, true and true

18. The method of optimizing MySQL

First, if the data exceeds a certain amount or volume, please split the table vertically or horizontally (the most effective optimization)

Second, there must be self increasing primary keys. It’s the fastest way to look up data by self increasing primary key.

Third, the common query field to establish a joint index, write SQL must respect the leftmost principle, use this index.

Fourth, don’t put logic operations in SQL. The implication is, don’t write too complex SQL, you can write complex SQL, and you can certainly achieve it through PHP.

19. What are the transactions in the database?

A transaction is a set of ordered database operations as a unit. If all operations in the group succeed, the transaction is considered successful, even if only one operation fails, the transaction is not successful. If all operations are completed,

Transactions are committed, and their modifications will affect all other database processes. If an operation fails, the transaction will be rolled back and the impact of the operation on the transaction will be cancelled.

20. Write a function to extract the file extension from a standard URL as efficiently as possible

It’s best to be able to write regularly. I’m not regular anyway. I use Baidu when I need it.

21. The parameter is an array of multiple dates and times, which returns the time closest to the current time

Traverse the array, find the current time difference, compare with the first, less than the first exchange position. Finally, take the first one.

22、echo、print、print_ The difference between R and R

These three together, the answer is, print_ R is a function, echo and print are structural languages.

As for their specific differences, please refer to:https://www.cnblogs.com/xiaotaoing/p/66873

23. What are the key and meaning in the header of HTTP protocol

This problem is very difficult. I can’t make it clear in a moment and a half. If you have done PHP restful interface development and stepped on the pit, you should be able to answer several commonly used keys.

24, binary tree before, after traversal code

  1. level traversal
  2. Preorder traversal
  3. Middle order traversal
  4. Postorder traversal

25. What’s the difference between the array structure of PHP and that of C language?

But in terms of PHP, the test is the implementation of PHP array. It can be simply considered that PHP’s array is a combination of hash bucket and cross linked list (in fact, it is a combination of array, list, hash table / associative array / dictionary hashtable). The advantage is that the query efficiency is very high, traversal is very convenient, the disadvantage is that it takes up more memory. (or space for time, after all, memory is not valuable now)

The array of C language is the sequence of fixed length and type.

26. How to realize the skip table of redis

Skip list is a kind of ordered data structure, which maintains multiple pointers to other nodes in each node, so as to achieve the purpose of fast access to nodes.

27. What is hash? How to store data after hash conflict?

28. Clustered index. What is the difference between clustered indexes?

29. How does B + tree search

What is the difference between array and hash?

31. Write a function to judge whether the following extension sign is closed. Left right symmetry is closed: (()), (()), (()), (()), (()), (()), (()), (()), (()), (())

32. Find out the non duplicate values in the array [1,2,3,3,2,1,5]

In the ordinary way, it must be easy.

What is your time complexity? In some cases, you write an algorithm, and then the interviewer will ask you to write out the time complexity expression of your algorithm

34. How to implement this kind of weakly typed variable in PHP?

The eight types of PHP have only one structure in essence.

35. In the process of HTTP communication, does the client or the server actively disconnect?

Three handshakes and four waves, and the state of each step.

It’s better to answer this question in one step and comprehensively. Generally, there is a client telling the server that I have finished sending things here. Can I disconnect. However, if the client sends fin and the server does not reply, it will try again until the timeout period is exceeded. The same is true for the server. If the time exceeds, the server will be disconnected.

36. What are the ways to initiate HTTP requests in PHP? What’s the difference between them?

  1. GET
  2. POST
  3. HEAD
  4. PUT
  5. DELETE
  6. OPTIONS
  7. TRACE
  8. CONNECT

37. There is a binary tree. Write the code to find out the shortest path from the root node to the flag node and print it out. There are several flag nodes. For example, 6 and 14 in the tree below are flag nodes. Please write the code to print the paths 8, 3, 6 and 8, 10, 14

A typical binary search tree. The basic problem of university data structure.

38. There are two files with the size of more than 1G, one line of data, and each line of data does not exceed 500 bytes. Some contents of the two files are exactly the same. Please write the code to find the same line and write it to the new file. The maximum allowable size of PHP is 255m.

The file is divided into several small files, hash value is calculated according to the content, and distributed to different files.

39. Please write two PHP functions supporting callback processing, and implement one PHP function supporting callback

array_map,array_filter, array_walk

40. Please write down two methods (code or ideas) to obtain all the files in the specified folder.

The core method is scanner and the core idea is recursion.

41. Please write down three methods or functions for intercepting file name suffixes (both PHP native functions and functions implemented by yourself)

echo substr(strrchr($file, '.'), 1);

echo substr($file, strrpos($file, '.')+1);

$arr=explode('.', $file);
echo $arr[count($arr)-1];

$arr=explode('.', $file);
echo end($arr);

echo strrev(explode('.', strrev($file))[0]);

echo pathinfo($file)['extension'];

echo pathinfo($file, PATHINFO_EXTENSION);

42. How can PHP distribute cookies for clients without using its own cookie function. For distributed system, how to save the session value.

This question is a little bit convoluted. The test is the basic knowledge of cookie and session. The server notifies the client to save the cookie through the set cookie command.

Just use the header function according to the rules of domain path expiration time.

Distributed system session, centralized processing. According to our company’s architecture, in order to achieve high availability and disaster tolerance, we provide a distributed signature verification service. Specifically, we can see the distributed service architecture of redis.

43. Please use shell to count the most visited URL addresses and corresponding IP addresses in nginx logs within 5 minutes?

44. Write a shell script to back up the specified MySQL Library (such as test) to the specified folder and package it, and delete the backup 30 days ago, then push the new backup to the remote server, and send the e-mail notification after the completion.

45. The difference between InnoDB and MyISAM engine in MySQL database

The difference is mainly in the storage structure and storage mode of data and index, as well as the support for transactions.

46. What is the process from the user entering the web address in the browser and entering to seeing the complete meeting.

How to get started. There is a big hole in this question, and the interviewer may ask you a lot of questions from this question.

Take PHP as an example: usually the simplest answer is to find the nearest DNS service from the user’s computer, and then resolve it to the corresponding IP address. Then both parties start to connect through HTTP, and then send the request information. When the server gets the request information, it begins to prepare the response information, which is transferred to frstcgi (php-fpm) through nginx, Then PHP starts to parse the framework, parse the request header, find the corresponding API, check the database, check the data, assemble HTML, assemble HTML, and return it to the user when it is finished. The user gets the returned data, the browser starts rendering the page, and JS starts loading.

47. How to analyze the performance of an SQL statement.

Explain, Baidu. (performance analysis statements are rarely used. In the design of MySQL table, some fields should be redundant as far as possible to avoid dealing with a large number of logical operations in MySQL. We do PHP service development, MySQL statements can be as simple as possible. Logic operation can be done in PHP.)

48. Ping a server does not work. Which command should I use to track the routing packets?

linux:traceroute,windows:tracert

49、$a=[0,1,2,3]; $b=[1,2,3,4,5]; $a+=$b; var_ What is the equivalent of dump ($a)?

Basic issues. The essence is the structure and characteristics of PHP array.

The result is 01235. There is a big difference between PHP’s numeric index and string index

50、$a=[1,2,3]; foreach ($a as &$v){} foreach ($a as $v){} var_ How much is dump $a;

122
There is a hole here. After foreach, the $Index and $value will not disappear and the last assignment will be retained.
After the first foreach here, the last element in the array becomes a reference, and the reference variable $V continues to exist and points to the last element of the array. In the second traversal, because the traversal variable name is $V, it means that the traversal value will be modified to the value of the last element until the last element (reference element) is traversed. At this time, the last element of the array has been modified to the value of the previous element, and the last assignment is self = = self. So the last one is the penultimate


More learning content can be accessedAs long as you can read it, your salary will go up a step

The above contents hope to help youA lot of PHPer always encounter some problems and bottlenecks when they are upgrading. They write too much business code and have no sense of direction. They don’t know where to start to improve. For this, I have sorted out some materials, including but not limited to:Distributed architecture, high scalability, high performance, high concurrency, server performance tuning, tp6, laravel, yii2, redis, spool, swoft, Kafka, MySQL optimization, shell script, docker, microservice, nginxAnd so on many knowledge points, advanced dry goods need can be free to share with you, need can join mePHP Technology Exchange Group953224940

Advanced PHP monthly salary 30K > > > architect growth path [free access to videos and interview documents]