Summary sharing of key PHP interview questions (2)

小云云
Release: 2023-03-22 06:08:01
Original
3773 people have browsed it

Earlier we shared with you the key PHP interview questions (1). This article mainly shares with you the summary of the key PHP interview questions (2). I hope it can help you.

1. Theoretical knowledge

1.1. Is PHP case-sensitive?

PHP is not case-sensitive for system functions, user-defined functions, class names, etc.

The variables and constants in PHP are Case-sensitive

The file name depends on the server operating system. It is distinguished in Linux but not in Win.

1.2, $_POST , the difference between $HTTP_RAW_POST_DATA and php://input?

$_POST:

is to get the form POST data, the media type is "application/x-www-form-urlencoded".

It means that the field name and value are encoded. Each key-value pair is separated by '&' characters. Key and value are separated by '='. Other special characters will be Encode using urlencode.

$HTTP_RAW_POST_DATA:

You can get the original POST data, but it needs to be turned on in php.ini and does not support enctype=" Data passed in multipart/form-data" method

php://input:

can obtain the original POST data and is better than $ HTTP_RAW_POST_DATA consumes less memory and does not support "multipart/form-data".

You can use the file_get_contents() function to get its content

#1.3. Can methods not defined statically be called in the form of "object name::method name"?

will generate a strict error, but code execution will continue. Refer to "PHP statically calling non-static methods". This article also talks about a concept "calling scope".
Static calling does not mean that there is::, it means static calling, but depends on the calling scope. The object pointed to by the $this pointer is the calling scope when this method is called.

Read this article for details: http://www.cnblogs.com/whoamme/p/3728052.html

1.4. Please Briefly explain your most proud development work

1.5. For websites with large traffic, what methods do you use to solve the problem of statistics of page visits

a. Confirm whether the server can support the current traffic.

b. Optimize database access. (Refer to 3.5)

#c. Prohibit external access to links (hotlinking), such as picture hotlinking.

d. Control file download.

e. Use different hosts to distribute traffic.

f. Use browsing statistics software to understand the number of visits and perform targeted optimization.

1.6. Please introduce the principle of Session

Because HTTP is stateless, the client and server will not change after a request is completed. There is no relationship anymore, no one knows anyone.

However, due to some needs (such as maintaining login status, etc.), the server and the client must be kept in contact, and the session ID becomes the medium for this contact.

When a user visits the site for the first time, PHP will use the session_start() function to create a session ID for the user, which is the unique identifier for the user,

Each visiting user will get a unique session ID. This session ID will be stored in the cookie in the response header and then sent to the client.

This way the client will have a session ID given to him by the site.

When the user visits the site for the second time, the browser will send the locally stored cookie (which contains the session ID obtained last time) to the server along with the request.

After receiving the request, the server will detect whether there is a session ID. If there is, it will find the response session file and read the information; if not, it will be the same as the first time. Create a new one as well.

1.7. Solution to session sharing problem

a. The client cookie is saved in a cookie-encrypted manner, each time Session information is written on the client and then submitted to the server again via the browser.

b. Session synchronization between servers uses the master-slave server architecture. When the user logs in on the master server, the session information is transferred to each server through a script or daemon process. From the server

c. Use the cluster to manage the session uniformly. When the application system needs session information, it directly reads it from the session cluster server. Currently, most of them use Memcache to manage the session. storage.

d. Persist the Session to the database. The database currently used when using this solution is generally mysql.

Refer to "Research on Session Sharing Implementation Solutions"

1.8. Tools for testing PHP performance and methods to find bottlenecks.

XHProf (refer here for windows installation method) is a layered PHP performance analysis tool. It reports the number of requests and various metrics at the function level, including blocking time, CPU time, and memory usage.

It has a simple HTML user interface. The browser-based performance analysis user interface can be easier to view and can also draw call diagrams. View parameter values.

1.9. Introduce the common principles of SSO (single sign-on).

SSO is a unified authentication and authorization mechanism. After passing the security verification in one application, you no longer need to log in again for verification when accessing protected resources in other applications.

Solve the problem that users only need to log in once to access all mutually trusted application systems without having to log in repeatedly.

The unified authentication system is one of the prerequisites for SSO. The main function of the authentication system is to compare the user's login information with the user information database and authenticate the user;

After successful authentication, the authentication system should generate a unified authentication mark (ticket) ), returned to the user. In addition, the authentication system should also verify the ticket to determine its validity.

Refer to "Single Sign-On SSO"

1.10. What are the characteristics of the PHP framework you have studied, what problems does it mainly solve, and how does it compare with other frameworks? differences.

1.11. Session usage plan that disables cookies

a. Pass the value through the url and append the session id to the url (disadvantages: There cannot be purely static pages in the entire site, because the purely static page session id will not be able to continue to the next page)

b. By hiding the form, put the session id in the hidden part of the form Submit the text box together with the form (disadvantage: it does not apply to non-form situations where the tag directly jumps)

c. Directly configure the php.ini file, Set session.use_trans_sid= 0 in the php.ini file to 1 (it seems not supported on win)

d. Save the Session ID in a file, database, etc., on a cross-page Manual calls during the process

1.12. What are the PHP caching technologies?

1. Full-page static caching, that is, all pages are generated into html static pages. The static pages are directly accessed when users visit, without going through the PHP server parsing process

2. Partial page caching, statically cache the parts of a page that do not change frequently, while blocks that change frequently are not cached, and are finally assembled together for display

3 . Data caching, the data requested through an id is cached in a php file. The id and the file are corresponding. The next time a request is made through this id, the php file is directly read

4. Query cache, similar to data cache, caches according to query statements;

5. Memory cache, redis and memcache

Refer to "Summary of the 9 major caching technologies in PHP"

1.13. What are the characteristics of JSON format data

a. JSON is a lightweight level data exchange format. It is based on a subset of ECMAScript.

b. JSON uses a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python etc.)

c. These features make JSON an ideal data exchange language. Easy for humans to read and write, and easy for machines to parse and generate (network transmission rate).

d. A collection of "name/value" pairs. In different languages, it is understood as an object, a record, a structure, and a dictionary. , hash table, keyed list, etc.

e. An ordered list of values, which is understood as an array in most languages

Refer to "Introduction to JSON"

##1.14, the difference between isset(), empty() and is_null

isset(): Only when null and undefined, returns false

empty(): "", 0, "0", NULL, FALSE, array(), undefined, all Returns true

is_null(): only determines whether it is null, and reports a warning if it is not defined

1.15, Advantages and Disadvantages of MVC

Advantages:

Split attention, loose coupling, logic reuse, standard definition

a. Developer You can only focus on a certain layer of the entire structure to facilitate the division of labor among multiple developers

b. You can easily replace the original layer of implementation with a new implementation

c. Reduce dependencies between layers

d. Conducive to the reuse of logic at each layer and standardization

e. Better support for unit testing

Disadvantages:

a. Clear architecture based on code At the expense of complexity, optimizing small projects may actually reduce development efficiency

b. It reduces the performance of the system. For example, business access to the database must now be completed through the middle layer

c. The control layer and the presentation layer are sometimes too close, resulting in no real separation and reuse

d. Sometimes it will lead to cascading modifications, if in the presentation To add a function to the layer, in order to ensure compliance with the layered structure, it may be necessary to add corresponding code to the corresponding control layer and model layer

Understanding of MVC:

MVC is the idea of ​​​​a development project. A project can be divided into three parts: data part (Model model), business logic part (Controller controller), external representation of data (View view),

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

1.16. What is the difference between single quotes and double quotes in PHP? Which one is faster?

Single quotes are faster

Data within single quotes will not be parsed (any variables and special escape characters), so it is faster Quick

Double quotation marks must first search whether there are variables in the statement. The data within the double quotation marks will be parsed. For example, the variable ($var) value will be substituted into the string. Special escape characters It will also be parsed into a specific single character

Here is a delimiter (heredoc syntax) "<<<",

Its function is to output what is inside it as it is, including newline format and so on. Any special characters do not need to be escaped, and the variables will be replaced by their values ​​normally

1.17. Brief description of GBK, GBK2312, BIG5, GB18030

GB2312 supports fewer Chinese characters. GBK has richer Chinese characters than GB2312, including all Chinese, Japanese and Korean Chinese characters.

Compared with GBK, GB18030 adds some ethnic minority Chinese characters and the Chinese character library is more diverse, which is rarely used by ordinary people

Generally, simplified Chinese uses GBK instead Traditional Chinese uses BIG5

1.18. What is the difference between interface and abstract class?

Abstract class:

Abstract class is a class that cannot be instantiated and can only be used as a parent class of other classes. Abstract class It is declared through the keyword abstract

Abstract classes are similar to ordinary classes, including member variables and member methods. The difference between the two is that the abstract class contains at least one abstract method

Abstract methods do not have a method body. This method is inherently to be overridden by subclasses

The format of an abstract method is: abstract function abstractMethod()

Subclasses inherit abstract classes using extends

Interface:

The interface is through the interface keyword To declare that the member constants and methods in the interface are public, the method does not need to write the keyword public

The method in the interface also has no method body, and the method in the interface is also born The

interface to be implemented by a subclass can implement multiple inheritance

The subclass implements the interface using implements

1.20. The difference between passing by value and passing by reference in PHP

Pass by value: Any changes to the value within the scope of the function will be ignored outside the function

Pass by reference: Any changes to the value within the function scope will also reflect these modifications outside the function

1.21, PHP5 constructor and destructor

__construct: This function will be treated as a constructor and will be executed when creating an object instance

#__destruct: PHP will destroy the object before it is destroyed Call this function. It is called the destructor

1.22. What is the garbage collection mechanism of PHP?

PHP is a managed language. In PHP programming, programmers do not need to manually handle the allocation and release of memory resources. This means that PHP itself implements a garbage collection mechanism (Garbage Collection)

The recycling algorithm used by PHP is the reference counting method. Each PHP variable is stored in a variable container called "zval".

A zval variable container, in addition to containing the type and value of the variable, also includes two bytes of additional information. The first one is "is_ref", which is a bool value used to identify whether this variable belongs to the reference set.

The second extra byte is "refcount", which is used to indicate the number of variables (also called symbols) pointing to this zval variable container.

Assigning one variable to another variable will increase the reference count (refcount)

When any variable associated with a variable container leaves Its scope (for example: when the function execution ends), or when the function unset() is called on the variable, "refcount" will be reduced by 1

#The variable container will become Destroyed at 0:00

1.23. Tell me a few design patterns you know?

Single case mode: Ensure that a class has only one instance and provide a global access point to access it, such as the database connection in the framework

Simple factory pattern: It has certain methods for creating objects. You can use factory classes to create objects instead of using new directly. For example, it will be used when initializing a database, such as MySQL, MSSQL

Strategy mode: For a set of algorithms, encapsulate each algorithm into an independent class with a common interface, such as entering Personal homepage, different displays and operations are given according to different viewers

Registration mode: Provides an orderly storage and management of a set of global objects (objects) in the program, For example, the Zend_Registry::set

adapter mode in the ZF framework: adapts different interfaces into a unified API interface. For example, data operations include mysql, mysqli, pdo, etc., the adapter mode can be used Unified interface

Observer pattern: An object makes itself observable by adding a method. When an observable object changes, it sends messages to registered observers. For example, to implement message push

Decorator mode: dynamically extend the function of the class without modifying the original class code and inheritance. For example, each Controller file of the framework will provide before and after methods.

Iterator mode: Provides a method to sequentially access each element in an aggregate object. In PHP, the Iterator class will be inherited.

Prototype mode: Implements a prototype interface that is used to create a clone of the current object. This mode is used when the cost of directly creating objects is relatively high. For example, an object needs to be created after an expensive database operation.

2. PHP coding

2.1. What is the difference between mysqli_real_connect() and mysqli_connect()?

a. mysqli_real_connect() requires a valid object created by mysqli_init()

b. mysqli_real_connect() can be used with mysqli_options() Used together to set different options for the connection

c. mysqli_real_connect() has a flag parameter

2.2. Traverse directories and subdirectories. File

You can use the scandir() or glob() function here. There is an article here that introduces the "Four Methods". There are two methods in the online code.

2.3. Given any URL, extract the extension contained in the URL. For example, "http://www.pwstrick.com/test.php?somevar" returns .php or php

## using 5 methods, pathinfo(), explode(), The combination of basename(), strpos() and substr(),

uses regular expressions (please refer to my previous article "Regular expressions in JavaScript and PHP") and parse_url(). Check out the code online.

2.4. How does PHP prevent SQL injection?

Use prepared statements and parameterized queries. The prepared statements and parameters are sent to the database server for parsing respectively, and the parameters will be treated as ordinary characters.

This method prevents attackers from injecting malicious SQL. You have two options to implement this method: PDO and MySQLI, see the code online. Refer to "How to Prevent SQL Injection in PHP"

2.5, the difference between include, require, include_once and require_once

a. include and require All import specified files. _once means that it is only introduced once, that is, what has been introduced before will not be introduced again.

b. Loading failures are handled differently:

include generates a warning when introducing a non-existing file and the script will continue to execute. included. To put it simply: take her with you!

require will cause a fatal error and the script will stop executing, depending on this file. To put it simply: I want her!

c. include is a conditional inclusion function, while require is an unconditional inclusion function.

d. The files that need to be referenced when include() is executed must be read and evaluated each time, and the files that need to be referenced when require() is executed are only processed once (actually when executing The content of the file that needs to be referenced replaces the require() statement)

e. include has a return value, but require does not. Refer to "The difference between include require include_once require_once in PHP"

2.6. Write some PHP magic methods

PHP Class methods starting with an underscore) are reserved as magic methods. Therefore, when defining class methods, it is recommended not to use __ as the prefix. Check the PHP manual.

2.7. Three ways to pass parameters to PHP using shell commands

Use $argc $argv; use getopt function (); Prompts the user for input and then gets the input parameters. Refer to "PHP Incoming Parameters"

2.8. Write a function to calculate the relative paths of two files, such as $a = "/a/b/c/d/e.php "; $b = "/a/b/12/34/c.php";

The calculated relative path of $a relative to $b should be "../. ./12/34/c.php"

First split the two strings into arrays with "/", and then use array_diff_assoc to first check the difference between the $a and $b arrays . Then do the difference set between $b and $a. Check out the code online.

2.9. Use php to write the code and web page address that displays the client IP and server IP

Client IP: $_SERVER[ "REMOTE_ADDR"]

Server IP: $_SERVER["SERVER_ADDR"]

##Web page address: $_SERVER["REQUEST_URI"]

The execution path of the current script: $_SERVER["SCRIPT_FILENAME"] or __FILE__

The name of the current script: $_SERVER["PHP_SELF" ] or $_SERVER["SERIPT_NAME"]

URL link to the previous page: $_SERVER["HTTP_REFERER"]

##2.10 , What is the role of error_reporting(2047)

error_reporting, set what kind of PHP errors should be reported, here refers to displaying all errors E_ALL

##2.11 , echo, print(), print_r(), printf(), sprintf(), var_dump(), what are the differences?

echo: It is a statement, not a function, there is no return value, and it can be output Multiple variable values, no parentheses required. Arrays and objects cannot be output, only simple types (such as int, string)

print: It is a statement, not a function. It has a return value of 1 and can only output one variable. No parentheses are needed. Arrays and objects cannot be output, only simple types (such as int, string) can be printed.

print_r: It is a function that can print composite types, such as stirng, int, float, array, object, etc. When outputting the array, it will be represented by a structure,

And you can use print_r($str,true) to make print_r not output and return the value after print_r processing

printf: It is a function that formats the text and then outputs it. (See C language)

sprintf: It is a function, similar to printf, but it does not print, but returns formatted text. Others are the same as printf.

var_dump: function, outputs the content, type of the variable or the content, type, and length of the string. Often used for debugging.

2.12, $a = 1; $x =&$a; $b=$a++; Find the values ​​of $b and $x

$b=1, $x=2

2.13. Functions for serializing and deserializing arrays in PHP and converting UTF-8 to gbk

serialize, unserialize, iconv("utf-8", "gbk",$strs)

##2.14, the functions of strlen() and mb_strlen What is it?

strlen() cannot correctly handle the placeholders of Chinese strings. For gb2312, the result is 2 times the number of Chinese characters, and for utf8, the result is 3 times the number of Chinese characters

mb_strlen() solves this problem very well. Its second parameter is to set the character encoding

2.15. Can be created with PHP Multi-level directory

mkdir($path, 0777, true);

2.16, the functions and differences of mysql_num_rows() and mysql_affected_rows()

Both return the number of rows in the result set. The difference is that the former is only valid for the select operation, while the latter is valid for the number of rows affected by update, insert, and delete

2.17. Please list all the string search algorithms you can think of, and add comments to briefly explain

Sequential search, binary search, block Search, hash table search

2.18. Write the result according to the following code

$a = 2;$b = &$a ;unset($a);echo$b;

Although unset is used to release the given variable, it only breaks the binding between the variable name and the variable content. is fixed, it does not mean that the variable content is destroyed. So the output result is "2".

$a = 2;$b = 3;$c = &$a;$c = 2;if(($a=5)>0 || ($b=$a)>0) {
$a++;$b++;

}echo$a.'-'.$b.'- '.$c;

Pay attention to the symbol "||" here. $a=5 already meets the conditions, so $b=$a does not need to be executed, then $ b is still 3.

After $a++ and $b++, both variables are increased by 1 and become 6 and 4. And $c already references $a, so the value also becomes 6. The final output result is "6-4-6". Refer to "Detailed Explanation of Using PHP Reference (&)"

2.19. Write a function to solve the problem of multiple threads reading and writing a file at the same time

First use fopen to open a file, then flock to lock it, then use fwrite to write the content, then flock to release the lock, and finally fclose to close the document. Check out the code online.

2.20. Method to set session expiration, corresponding to function

a. setcookie() directly sets the life cycle of session_id.

b. Use session_set_cookie_params() and session_regenerate_id(true). When it is true, change the value of session_id and clear the current session array.

View the online code.

2.21. PHP method of obtaining file content, corresponding function

a. file_get_contents obtains the content of the file (can be obtained with get and post method to obtain), the entire file is read into a string

b. Use fopen to open the url, and obtain the content using the get method (with the help of the fgets() function)

c. Use the fsockopen function to open the url (can be obtained by get and post), and obtain the complete data by get, including header and body

d. Use The curl library obtains content. Before using the curl library, you need to check php.ini to see if the curl extension has been turned on

2.22. What are the common PHP array functions?

a. Basic functions of array operations (array_values, array_keys, array_flip, array_search, array_reverse, in_array, array_key_exists, array_count_values)

b. Segmentation and filling of arrays (array_slice, array_splice, array_chunk)

c. Arrays and stacks, queues (array_push, array_pop, array_shift, array_unshift)

#d. Array sorting (sort, asort, ksort)

e. Array calculation (array_sum, array_merge, array_diff, array_intersect)

f. Other array functions (array_unique, shuffle)

2.23. Write a code to upload files

POST method upload, Enables users to upload text and binary files. Using PHP's authentication and file operation functions, you can fully control who is allowed to upload and how the file is processed after it is uploaded.

Receive files uploaded to the server via HTTP through $_FILES. The uploaded content is stored in $_FILES['xx']['tmp_name'], and then uploaded through move_uploaded_file. The files are moved to the new location.

When I was looking at some packaged upload classes, I saw a function strrchr, which searches for the last occurrence of a specified character in a string and uses this function to get the suffix.

2.24. Write a regular expression to filter all JS/VBS scripts on the web page (that is, remove the tags and their contents)

/<[^>].*?>.*?<\/>/si. Check out the regex online tool for ready-made regex instructions.

2.25. Use PHP to print out the time of the previous day in the format of 2006-5-10 22:21:21

echo date('Y-m-d H:i:s', strtotime('-1 day')); See more Date/Time functions.

2.26. What is the difference between foo() and @foo()?

foo() will execute this function. Any interpretation errors, syntax errors, and execution errors will be displayed on the page.

@foo( )When executing this function, the above error message will be hidden

2.27. What are the differences between sort(), asort(), ksort(), arsort(), and rsort()?

sort: Sort the array. When the function ends, the array cells will be rearranged from lowest to highest

rsort: Sort the array Reverse sort

asort: Sort the array and maintain the index relationship

arsort: Sort the array in reverse and maintain the index relationship

ksort: Sort the array by key name and retain the association between key name and data. It is mainly used to associate arrays

2.28. What is a variable variable? What are the input values ​​for the following program?

A variable variable is to obtain the value of an ordinary variable as the variable name of the variable variable. The output value is "ok".

$str = 'cd';

$$str = 'hotdog';

$$str = 'ok';echo$cd;

2.29. What will echo count("abc") output?

#The count() function calculates the number of cells in an array or the number of attributes in an object, usually an array()

For objects , if SPL is installed, count() can be called by implementing the Countable interface. This interface has only one method count(), which returns the return value of the count() function.

If the parameter is not an array type or an object that implements the countable interface, 1 will be returned. There is only one exception. If the parameter is NULL, the result is 0.

2.30. What is the role of the GD library?

The GD library provides a series of APIs for processing images. You can use the GD library to process images or generate images.

On websites, the GD library is usually used to generate thumbnails or to add watermarks to images or to generate reports on website data.

3. Database

3.1. Suppose there is a database with a data volume of tens of millions. Through monitoring, it is found that 90% of the query requests They all point to the same part of data, and this part of data only accounts for 1% of the entire database capacity.

a. This 1% data supports 90% of the query work. When Jianyi is independent, this convenient data can be stored in the data buffer to improve query efficiency.

b. Sub-database: The performance is rapidly improved. If the efficiency still cannot improve, you can consider doing some nosql caching on the 1% of the data.

c. Table sharding: It can obtain certain horizontal expansion capabilities when the database lacks a cluster solution, and the load can also be shared to multiple physical devices. From this perspective It can also solve some performance bottlenecks.

d. If conditions permit, this application can also be solved through caching solutions, such as caching 1% of the result set through memcached and redis.

Refer to "ChinaUnix Q&A Discussion" and "Dewen Discussion"

3.2. How does MySQL divide databases and tables?

Refer to "Global ID Generation Scheme in MySQL Sub-database and Table Sub-Environment", "Lessons and Experience of the First Database Sub-table", "Some MySQL Sub-database and Table Sub-tables" Tips》

3.3. What are the MySQL database storage engines?

MyISAM, InnoDB, HEAP, BOB, ARCHIVE, CSV, etc.

3.4. The difference between MyISAM and InnoDB

a. Storage structure: MyISAM is stored in three files on the disk. All tables in InnoDB are stored in the same data file, generally 2GB

b. Storage space: MyISAM can be compressed and has smaller storage space. InnoDB requires more memory and storage, and it will establish its own dedicated buffer pool in main memory for caching data and indexes.

c. Transaction support: MyISAM does not provide transaction support. InnoDB provides transaction support for transactions, foreign keys and other advanced database features.

d. AUTO_INCREMENT: MyISAM can create a joint index with other fields. InnoDB must contain an index with only this field.

e. Table lock differences: MyISAM only supports table-level locks. InnoDB supports transactions and row-level locks.

f. Full-text index: MyISAM supports full-text index of FULLTEXT type. InnoDB does not support it.

g. Table primary key: MyISAM allows tables without any indexes and primary keys to exist. The indexes are the addresses where rows are saved. If InnoDB does not set a primary key or a non-empty unique index, it will automatically generate a 6-byte primary key (not visible to the user). The data is part of the primary index, and the additional index saves the value of the primary index.

h. The specific number of rows in the table: MyISAM saves the total number of rows in the table. InnoDB does not store the total number of rows in the table. But after adding the wehre condition, myisam and innodb handle it in the same way.

i. Foreign keys: MyISAM does not support it. InnoDB supports

j. CURD operation: MyISAM If you perform a large number of SELECTs, MyISAM is a better choice. If your data performs a lot of INSERT or UPDATE, you should use an InnoDB table for performance reasons.

Reference "MyISAM and InnoDB in MySQL Storage Engine"

3.5. What are the MySQL data types?

Refer to "SQL Data Types"

3.6. MySQL database is used as the storage of the publishing system. The increment of more than 50,000 items per day is expected. After three years of operation and maintenance, how to optimize?

a. Design a good database structure, allow partial data redundancy, and try to avoid join queries to improve efficiency.

b. Select the appropriate table field data type and storage engine, and add indexes appropriately.

c. Mysql library master-slave reading and writing separation.

d. Find regular tables and reduce the amount of data in a single table to improve query speed.

e. Add caching mechanisms, such as memcached, apc, etc.

f. For pages that do not change frequently, generate static pages.

g. Writing efficient SQL

3.7. What security should be considered for SQL statements?

Mainly to prevent injection, escape special characters such as ' " / \, pay attention to html filtering when submitting data, pay attention to comments like --,#, pay attention to subqueries and Some mysql functions sleep, load_file, etc.

3.8. Is the function that MYSQL uses to obtain the current time? The function that formats dates?

##now( ); date_format(); View more MySQL built-in functions

##3.9. Bottleneck of relational database

##Memcached+MySQL

With the increase in visits, almost most websites using MySQL architecture have begun to have performance problems on the database. Programmers have begun to use caching technology extensively to relieve the pressure on the database and optimize the database. Structure and index. As an independent distributed cache server, Memcached provides a shared high-performance cache service for multiple web servers. On the Memcached server, multiple Memcached cache services are developed based on the hash algorithm. Expansion, and then consistent hashing appeared to solve the disadvantages of a large number of cache failures caused by re-hash caused by adding or reducing cache servers.

MySQL master-slave read-write separation

#.

##Memcached can only relieve the reading pressure of the database. The concentration of reading and writing on one database makes the database overwhelmed. Most websites have begun to use master-slave replication technology to achieve read-write separation to improve read-write performance. And the scalability of reading database

##Sub-table and sub-database

As web2.0 continues to develop rapidly, the writing pressure of the MySQL main database begins to appear bottlenecks, and the amount of data continues to surge. Since MyISAM uses table locks, serious lock problems will occur under high concurrency. , a large number of high-concurrency MySQL applications began to use the InnoDB engine instead of MyISAM. At the same time, it has become popular to use sub-tables and sub-databases to alleviate write pressure and expansion problems of data growth.

The scalability bottleneck of MySQL

MySQL application development in a large data volume and high concurrency environment is becoming more and more complex and complex. Technically challenging. Mastering the rules of sub-table and sub-database requires experience. Sub-databases with sub-databases and tables will face expansion problems at a certain stage. There is also a change in requirements, which may require a new sub-library method. MySQL databases also often store some large text fields, resulting in very large database tables, which makes database recovery very slow and makes it difficult to quickly restore the database. Under big data, IO pressure is high and table structure changes are difficult, which are exactly the problems faced by developers currently using MySQL.

3.10. What is a relational database?

Relational database is a database that supports the relational model. Simply put, the relational model refers to the two-dimensional table model.

Relational databases store data in the form of rows and columns to make it easier for users to understand. This series of rows and columns is called a table, and a group of tables makes up a database.

4. Linux basics

4.1. Some methods to view the current system load information under Linux

Refer to "Viewing System Resources and Loads, and Performance Monitoring under Linux"

4.2. Basic shortcut keys for vim

Refer to "History The most complete Vim shortcut key map - from entry to advanced》

4.3. Please explain the purpose of the following 10 shell commands: top, ps, mv, find, df, cat, chmod, chgrp, grep, wc

top to check the resources occupied by system processes. ps displays detailed process information.

mv is to rename a file or directory, or to transplant a file from one directory to another.

find Find a file or directory.

df Check the disk space usage of the file system.

cat displays the file contents, creates a new file, and merges the file contents.

chmod changes the access permissions of a file or directory.

chgrp changes the group to which a file or directory belongs.

grep is a powerful text search tool.

wc counts the data information of the specified file, such as the number of lines and the number of bytes

4.4. What is the core file and what is it used for?

core is the kernel of the unix system. When your program's memory exceeds the bounds, the operating system will terminate your process and dump the current memory status into the core file for further analysis.

Programmers can find the problem through the core file. It records a detailed status description when the program hangs.

5. Network Basics

5.1. Write the purpose and default port of the following services ftp, ssh, http, telnet, https

ftp file transfer protocol is a common file copy method. The default is 20 for data connection and 21 for control connection port.

Ssh connects to the server to perform operations. The default port number is 22.

HTTP Hypertext Transfer Protocol provides a method to publish and receive HTML pages. The port number is 80

The Telnet protocol is a member of the TCP/IP protocol family. It is the standard protocol and main method for Internet remote login services. The default port is 23

HTTPS is based on The security-targeted HTTP channel is simply a secure version of HTTP. The default port is 443

5.2. Write out all the HTTP return status values ​​you can think of and explain their uses (such as : Returns 404 indicating that the page cannot be found)

200 OK The request is successful (followed by the response document to the GET and POST requests)

301 Moved Permanently The requested page has been moved to the new url

302 Found The requested page has been temporarily moved to the new url

304 Not Modified, the server tells the client that the original cached document can continue to be used

401 Unauthorized The requested page requires a username and password

403 Forbidden Access to the requested page is prohibited

500 Internal Server Error, the request is not completed. The server encountered an unpredictable situation

502 Bad Gateway, the request was not completed. The server received an invalid response from the upstream server

503 Service Unavailable The request was not completed. The server is temporarily overloaded or crashed

For more status codes, please refer to "HTTP Status Messages"

5.3. What is the difference between POST and GET?

a. GET is to obtain data from the server, and POST is to transmit data to the server

#b. GET is to send the HTTP protocol through the URl Parameters are passed for reception, while POST is entity data, submitted through the form

c. The amount of data transmitted by GET is small and cannot be larger than 2KB. The amount of data transmitted by POST is large and is generally unrestricted by default. But in theory, the maximum size in IIS4 is 80KB, and in IIS5 it is 100KB

d. GET security is very low, and POST security is high

5.4. Please write the HTTP header and meet the following requirements:

1) This is a post request

2) Target: http://www.example.com:8080/test

3) POST variable: username: test pwd: test2 intro: Hello world!

4) Contains the following COOKIE information: cur_query: you&me

POST http://www.example.com:8080/test HTTP/1.1

Cookie:cur_query=you&me

username=test&pwd:=test2&intro=Hello world!


View more properties "HTTP Header Detailed Explanation"

6. Server Basics

##6.1. Comparison of the advantages and disadvantages of Apache and Nginx

a. Advantages of nginx over apache:

It is lightweight and takes up less memory and resources than apache. Highly modular design, writing modules is relatively simple

Anti-concurrency, nginx handles requests asynchronously and non-blocking, multiple connections (10,000 levels) can correspond to one process, while apache is blocking It is a synchronous multi-process model. One connection corresponds to one process. Under high concurrency, nginx can maintain low resources, low consumption and high performance.

nginx processes static files well, and Nginx has static processing performance More than 3 times higher than Apache

b. Advantages of apache over nginx:

Apache's rewrite is more powerful than nginx's rewrite. There are many modules. You can find basically everything you can think of. It is relatively stable and has fewer bugs. nginx has relatively more bugs

c. Reason:

Benefit from Nginx using the latest epoll (Linux 2.6 kernel) and kqueue (freebsd) network I/O model, while Apache uses the traditional select Model.

Currently, Squid and Memcached, which can withstand high concurrent access under Linux, both use the epoll network I/O model.

To handle the reading and writing of a large number of connections, the select network I/O model adopted by Apache is very inefficient.

Refer to "Comparison of the Advantages and Disadvantages of Apache and Nginx"

##6.2. The difference between cgi and fastcgi

CGI: It was used more in 2000 or earlier. In the past, web servers generally only processed static requests. Based on the content of this request, the web server would fork a new process to run external C programs ( Or perl script...), this process will return the processed data to the web server. Finally, the web server will send the content to the user, and the process that was just forked will also exit. If the user requests to change the dynamic script next time, the web server will fork a new process again, and the cycle will continue.

Web built-in module: Later, a more advanced way appeared, the web server can have a built-in perl interpreter or php interpreter. In other words, these interpreters are made into modules, and the web server will start these interpreters when it starts. When new dynamic requests come in, the web server parses these perl or php scripts by itself, eliminating the need to re-fork a process and improving efficiency.

fastcgi: When the web server receives a request, it will not re-fork a process (because this process is started when the web server starts and will not exit), web The server directly passes the content to this process (inter-process communication, but fastcgi uses another method, tcp communication). This process processes the request after receiving it, returns the result to the web server, and finally waits for the next request. Come in, not out.


Refer to "What is the difference between fastcgi and cgi"

6.3. The difference between Memcached and Redis

a. In Redis, not all data is always stored in memory. This is the biggest difference compared with Memcached.

b. Redis has the characteristics of a database in many aspects, or is a database system, while Memcached is just a simple K/V cache.

c. In data of more than 100k, Memcached performance is higher than Redis.

d. If we want to talk about memory usage efficiency, if we use simple key-value storage, Memcached has higher memory utilization, and if Redis uses hash structure for key-value storage , due to its combined compression, its memory utilization will be higher than Memcached. Of course, this depends on your application scenario and data characteristics.

#e. If you have requirements for data persistence and data synchronization, it is recommended that you choose Redis, because Memcached does not have these two features. Even if you just hope that cached data will not be lost after upgrading or restarting the system, it is wise to choose Redis.

f. There is not much difference between Redis and Memcache in terms of writing performance, but Memcache is stronger in terms of reading performance, especially batch reading performance.

Refer to "The Difference between Redis and Memcached"

6.4. What are the advantages and disadvantages of PHP?

Advantages:

a. The syntax is simple, you can get started quickly, and there are many convenient development tools, such as Zend Studio , EclipsePHP Studio, etc.

b. Cross-platform and free. You can quickly build LAMP (Linux Apache MYSQL, PHP) and support many mainstream database systems, such as MYSQL, Oracle, PostgreSQL, etc.

c. Supports current mainstream technologies, such as WebService, XML, AJAX, etc.

d. PHP already has a very mature object-oriented system and can support object-oriented Development (PHP5)

#e. There are many good existing frameworks, open source forums, and blogs, etc.

f. Continue The update and maintenance of PHP, as well as the support of the community and the joint efforts of many technology enthusiasts, have made PHP widely used. Many well-known websites are also using PHP as a development language

Disadvantages :

a. The support for multi-threading is not very good. We can only do some simple simulated threads

b. The syntax is not rigorous enough. If When doing C++ in the past, Java is very familiar. For example, if a variable has not been defined, you may directly use

c. Perhaps the most painful thing for experienced PHP programmers is PHP's interpretation and operation mechanism. This operating mechanism ensures that after each PHP page is interpreted and executed, all related resources will be recycled. In other words, PHP has no way to make an object resident in memory at the language level. In PHP, all variables are page-level. Whether they are global variables or static members of the class, they will be cleared after the page is executed. Take JSP as an example. In JSP, the scope of Java Bean has four valid values: Page, Application, Session, and Request, which correspond to the four lifetimes of page, program, session, and request respectively. But in PHP, there is only one lifetime of Page.

Related recommendations:

Sharing of key PHP interview questions (1)

The above is the detailed content of Summary sharing of key PHP interview questions (2). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!