Home >Backend Development >PHP Tutorial >PHP basic interview questions
This article shares with you some basic interview questions about PHP. Friends who are interested can take a look
##csrfWhat is:
CSRF cross-site request forgery, 1. User C opens the browser, visits trusted website A, enters the username and Password request to log in to website A;2. After the user information is verified, website A generates cookie information and returns it to the browser. At this time, the user successfully logs in to website A and can send requests to website A normally;3. Before the user exits website A, he opens a TAB page in the same browser to visit website B; 4. After website B receives the user's request, it returns some offensive code and Make a request to access third-party site A;5. After receiving these offensive codes, the browser carries the cookie information to website A according to the request of website B without the user’s knowledge. ask. Website A does not know that the request is actually initiated by B, so it will process the request with C's permissions based on user C's cookie information, causing the malicious code from website B to be executedPHP and MYSQL Transaction processing:
1. Use begin, rollback, and commit to implement begin to start a Transactionrollback Transaction rollbackcommit Transaction confirmation2. Use set directly to change the automatic commit mode of mysqlThe 4 major characteristics of transactions (ACID):
Atomicity: A transaction is a logical unit of work of the database, and all modifications to the database are executed. Or don't execute them all. Consistemcy: Before and after the transaction, the state of the database satisfies all integrity constraints. Isolation: Concurrently executed transactions are isolated, and one does not affect the other. If there are two transactions, running at the same time, performing the same function, the isolation of the transactions will ensure that each transaction in the system thinks that only that transaction is using the system. This property is sometimes called serialization. To prevent confusion between transaction operations, requests must be serialized or deserialized so that there is only one request for the same data at the same time. By setting the isolation level of the database, different isolation effects can be achieved. Durability (Durability): After the transaction is completed, the changes made to the database by the transaction are permanently saved in the database and will not be rollback.xss
How to prevent:
XSS is also called CSS , full name CrossSiteScript, cross-site scripting attackPrevent: script injection, escape filtering script tags.The difference between union
and unionall: union removes duplicates, unionall does not remove duplicates
RBAC
Role-based permission control: 5 tables User table, role table, function table, and more There are tables related to each other: user and role table, role and function table
redis
Persistence: Memory snapshot (RDB) RDB persistence can generate point-in-time snapshots of the data set within a specified time interval
Log (AOF) AOF persistence records all write operations performed by the server commands and restore the data set by re-executing these commands when the server starts.Sub-table:
Reduce the burden on the database and shorten the query time.
vertical division: Vertical division is the field according to the field. Horizontal division: Put the data line in two independent tables according to the values of one or more data.How to ensure that the inserted id
is unique in horizontal table sharding?You can create a new ID service and save the user's ID in the database or redis.
jquery
Selector: 1.Element 2.Attribute 3.id 4.Class 5.Global.
Inline elements and in-block elements
Out Out Out Out Out Out Out Out Out ” ” h1>
Conversion: display:inline,block,inline-block.
Difference:
block,
① Always start at the new line, occupying a whole line;
② height, high and external distance and inner side spacing can be controlled; Like the browser width, it has nothing to do with content;
④ It can accommodate inline elements and other block elements.
Line,
① and other elements are on the same line;
②Height, line height and outer and inner margins can be changed;
③ The width is only related to the content;
④ Inline elements can only accommodate text or other inline elements.
Group query
: orderby
The number of men and women in the table is 20 -30
:
select count(sex) from table where age between 20 and 30 group bysex
##ORM
:
Object Relational Mapping (ORM) mode is a technology that solves the mismatch between object-oriented and relational databases
Linux
View port: brush selected file: view process:
netstat-ntlp //View all current tcp ports· netstat-ntulp | grep80
#Linux
View how many commands have been executed: history
File operation function: open Open the file
fstat Get the file file Read the entire file into an array fclose Close the filefwrite Write to a file (safe for binary files)
file_get_contents() reads the entire file into a stringSeveral ways to open a file:
Fopen(), file_get_contents() Read and write, appendphp Delete folder command
Unlink();Chinese string interception:mb_substr
mb_substr($str,$start, $length, $encoding) $str, the string that needs to be truncated $start, the starting point of truncation, The starting point is 0 $length, the number of words to be intercepted$encoding, web page encoding, such as utf-8, GB2312, GBK
The difference between D
and M
: M instantiates the base class, and D can instantiate the custom classtable Interlaced color change:
Use JQ to identify the even and odd numbers of table tr td, and give different numbers to the corresponding odd and even numbers. CSS style, through different backgrounds, can achieve the effect of changing colors between rows. When the mouse passes by, JQ calls the trtd background set separately, so that the background color changes when the mouse passes by.ajax
Synchronous and asynchronous:
Synchronously wait for the return result from the server and then perform other operationsAfter sending the request asynchronously, do not wait for the return result from the server and directly perform other operations
The default is: asynchronous
LinuxView all files: ls
Set up a p on another p:
The larger the z-index value is, the higher it is
ob Function:
ob_start (); //Open an output buffer. All output information is no longer sent directly to the browser, but is saved in the output buffer.
Ob_clean(); //Delete the contents of the internal buffer without closing the buffer (no output).
Ob_end_clean(); //Delete the contents of the internal buffer and close the buffer (no output).
Ob_get_clean(); //Return the contents of the internal buffer and close the buffer. Equivalent to executing ob_get_contents() and ob_end_clean()
ob_flush(); //Send the contents of the internal buffer to the browser, delete the contents of the buffer, and do not close the buffer.
Ob_end_flush(); //Send the contents of the internal buffer to the browser, delete the contents of the buffer, and close the buffer.
Ob_get_flush(); //Return the contents of the internal buffer, close the buffer, and then release the contents of the buffer. Equivalent to ob_end_flush() and returns the buffer contents.
flush(); //Output the content released by ob_flush and the content not in the PHP buffer to the browser; refresh the content of the internal buffer and output it.
Ob_get_contents(); //Return the contents of the buffer without output.
Ob_get_length(); //Returns the length of the internal buffer. If the buffer is not activated, this function returns FALSE.
ob_get_level(); //Return the nestinglevel of the output buffering mechanism.
ob_get_status(); ##3.
How to make a shopping cart? process. .
1. Add the product to the shopping cart 1. First add a link on the page
1. Get the product id first 2. Query the product by ID from the database. 3. Add the product to the shopping cart a. Get the shopping cart from the session, if not, create a new one b. Determine whether the product is in the shopping cart Does it exist? If not, the quantity is 1. If it exists, the quantity is increased by 1 c. Reload the shopping cart into the session. Problem: Our shopping uses a HashMap collection, the key is unique, the only way to ensure the key is through hashCode and equals methodSo we are using When rewriting, we need to rewrite the hashCode and equals methods of the Product class. When we rewrite, we only need to compare the id values.2. Display shopping cart items
Our shopping cart exists in the session. We only need to collect the Cartt Map in the session on the cart.jsp page and display it.1. Operate the items in the shopping cart
2. When clicking + or -, you can modify the quantity of items in the shopping cart 3. When clicking + or- When the button is pressed, we will call a function in javascript. changeCount(); Through this function, we send a request to the server, obtain the data in the shopping cart from the session on the server side, and modify the specified number of items in the shopping cart based on the submitted data before returning to the shopping cart page for display.How to get the sales volume of the last month? Three months? What about a year?
Check a certain field in the database
How to retrieve 30 million pieces of data within 3 seconds? What index to create?
Ordinary index
Index type:
Ordinary index, unique index, primary key index, combined index
The difference between redis and memecache is:
1. Storage method:
memecache stores all the data in the memory and will hang up after a power outage. The data cannot exceed the memory size. Part of redis is stored on the hard disk, which ensures data persistence.
2. Data support type:
Redis has much more data support than memecache.
3. The underlying model is different:
The new version of redis directly builds the VM mechanism by itself, because if the general system calls system functions, it will waste a certain amount of time to move and request.
4. Different operating environments:
Currently redis officially only supports LINUX, thus eliminating the need for support for other systems. In this way, you can better devote your energy to this system environment Optimization, although later a team from Microsoft wrote a patch for it. But it is not placed on the trunk
SKUHow to do it:
Attribute specifications.
In fact, sku is the product inventory unit, including the product table, product attribute table, product table
tp configuration file: common/config.php
php Data type:
Four scalars Type:
boolean (Boolean type)
integer (integer type)
float (floating point type, also called double)
string (character String)
Two composite types:
Array (array)
Object (object)
Finally, there are two special types:
Resource (Resources)
# NULL (NULL)
# Series Single Mode: ## The main characteristics of the single example mode It is "three private and one public":
You need a private static member variable that holds the only instance of the class
The constructor must be declared private to prevent external programs from newing an object and losing the singleton The meaning of
The cloning function must be declared private to prevent the object from being cloned
A public static method (usually named getInstance) must be provided to access this instance, thereby returning a reference to the unique instance .
Query the number of men and women between 20-30
://select count(sex) from Table where age between 20 and 30group by sex
Select count(*) from table name where age between 20 and 30 group by age. Group by
There are three access modifiers in PHP
, namely: public (public, default)
protected (protected) )
private (private)
Scope of access modifiers:When a member of a class is declared as a public access modifier , this member can be accessed and manipulated by external code.
private (private)
Members defined as private are visible to all members within the class and have no access restrictions. Access is not allowed outside the class.
protected (protected)
protected is slightly more complicated. Members declared as protected only allow access by subclasses of this class.
mysql int
Storage: bigint storage size is 8 bytes. The storage size of int is 4 bytes. The storage size of smallint is 2 bytes. tinyint Integer data from 0 to 255. Storage size is 1 byte. Scope of cookie: domain itself. All domain names under domain. It is to set a permission for the cookie. When domain is set to empty, domain defaults to the current domain name, and subdomains under this domain name can receive cookies. But when the domain parameter sets its subdomain name, all domain names cannot be received, including that subdomain name. ##linux View the log file content command ## Top View Memory # DF-LH View Disk PS-A View All Process Variable usage $: When defining and using constants There is no need to use the $ sign. The value of a constant must be a fixed value and cannot be a variable, class attribute, the result of a mathematical operation or a function call. Constants can also be defined in interfaces. Abstract classes cannot be instantiated. Abstract classes can have static methods. There can be no abstract methods in abstract classes. Ordinary methods are stored in the class, and there is only one copy. Static methods are also stored in the class, and there is only one copy. Ordinary methods require objects to call and $this needs to be bound. That is, ordinary methods must have objects, and then let the objects call them. And static methods do not belong to Which object, so there is no need to bind $this. That is, you can call it without an object. Static members: They can be accessed without instantiation. The static member variables of the class only belong to this Class Class members: one is defined in the class, and the other is defined in the constructor. Functions exist alone, while methods depend on the class and can only be called through objects. Whether functions can be defined in class files: No (1) Pass by value: Any changes to the value within the function range will be ignored from the outside of the function Series. These modifications can also be reflected outside the function (3) Advantages and Disadvantages: A: When passing by value, PHP must copy the value. Especially for large strings and objects, this can be a costly operation. B. Passing by reference does not require copying the value, which is very beneficial to performance improvement. 1. Use JS to disable the button after clicking it once. Using this method can prevent multiple clicks from happening 2. Set the session value. After submitting it once, delete it. If there is no session value, do not allow submission. 3cookies are the same strlen();strpos();echo();implode();trim(); etc.,,, strrev, mb_string; and http1.1: HTTP1.0 regulations The browser only maintains a short-term connection with the server. Each request of the browser needs to establish a TCP connection with the server. The server immediately disconnects the TCP connection after completing the request processing. The server does not track each customer nor does it Log past requests. HTTP1.1 supports persistent connections. Multiple HTTP requests and responses can be transmitted on a TCP connection, reducing the consumption and delay of establishing and closing connections. HTTP1.1 also allows the client to make the next request without waiting for the result of the previous request to be returned, but the server must send back the response results in the order in which the client request is received, To ensure that the client can distinguish the response content of each request, which also significantly reduces the time required for the entire download process HTTP1.0 does not support the Host request header field. H The Host request header field is added in TTP1.1. The difference between global variables and local variables: 1. Different scopes: The scope of global variables is The entire program, while the scope of local variables is the current function or loop, etc. 2. The memory storage methods are different: global variables are stored in the global data area, and local variables are stored in the stack area 3 .Different lifetimes: The lifetime of global variables is the same as that of the main program. It is destroyed when the program is destroyed. Local variables are inside the function or inside the loop and cease to exist when the function exits or the loop exits 4. They are used in different ways: global variables can be used in all parts of the program after they are declared, but local variables can only be used locally. Within the function, local variables will be used first before global variables One thing to note is that local variables cannot be assigned the value of a global variable with the same name. Front-end optimization: First: content-oriented optimization 1. Reduce HTTP request 2. Reduce DNS lookup 3. Avoid redirection 4. Use Ajax caching 5. Lazy loading of components 6. Preload components 7. Reduce the number of DOM elements 8. Split components into multiple domains 9. Minimize the number of iframes 10. Don’t get http 404 errors Second: Server-oriented 1. Reduce cookies 2. Use domain name-independent # for Web components ##What is cache avalanche? How to avoid it? tp Routing mode: niginxHow to configure the port number: jqGet the second row of the table tag: What is a variable variable: Check whether the port is occupied: Modify permissions Modify owner Modify user group netstat –apn chmod chown chgrp View process Top pa aux|grep Add execution permissions for everyone: chmod-x MysqlMaster-slave replication: From the library, generate two threads, one I/O thread, and a SQL thread; I/O thread to request the binlog of the main library, and write the obtained binlog logs log (relay log) file; The main library will generate a log dump thread, which is used to transfer binlog to the slave library i/o thread; The SQL thread will read the relay log The log in the file is parsed into specific operations to achieve consistent master-slave operations and consistent final data; Commands required for master-slave replication: showmaster status; startsalve; stopsalve; flushprivileges; GRANTREPLICATIONSLAVE,RELOAD,SUPER ON *** ## master_user='mysql_backup', master_password='123456', master_log_file='mysql-bin.000001', master_log_pos = 3696; Create a master table, and the ids are distributed from the master table. 1. Authorize accounts on two machines respectively: grant replication slave, file, select on *.* to'repl'@'10.17.%'identified by 'xxxx' 2. Configuration file/etc/my.cnf, when using the main library configuration file Basically, add the following configuration items ##nginx Reverse proxy: Add weight (the default is rr+weight) on the basis of rr. The weight polling is proportional to the access. The larger the value, the more allocated it will be. More, the weight can be set according to the server configuration, which can solve the problem of uneven server performance and request allocation (3) ip_hash It can improve the efficiency of the back-end cache server. nginx itself does not support url_hash, you need to download the hash software (6) least_conn The minimum number of connections, whichever connection has fewer connections will be allocated Device (7) consistent_hash Consistency algorithm 3, Load balancing: Load balancing deployment method: Routing mode (recommended) Bridge mode Service direct Return mode Round-robin balancing: Each request from the network is assigned to the internal server in turn, from 1 to N and then starts again. This balancing algorithm is suitable for situations where all servers in the server group have the same hardware and software configuration and the average service requests are relatively balanced. Weight round-robin balancing: According to the different processing capabilities of the server, different weights are assigned to each server so that it can accept services with the corresponding number of weights. ask. For example: the weight of server A is designed to be 1, the weight of B is 3, and the weight of C is 6, then servers A, B, and C will receive 10%, 30%, and 60% of service requests respectively. This balancing algorithm ensures that high-performance servers receive more utilization and prevents low-performance servers from being overloaded. Random balancing: Randomly distribute requests from the network to multiple internal servers. Weight random balancing: This balancing algorithm is similar to the weighted round-robin algorithm, but it is a random selection process when processing request sharing 4 The difference between load balancing and reverse proxy Reverse proxy is a method to achieve load balancing. Let’s talk about reverse proxy first. When the user makes a request, he first sends the request to the proxy server, and then the proxy server requests the real server according to the algorithm, and finally returns it to the user. This approach, firstly, improves security; secondly, it shares user requests through multiple real servers and achieves load balancing. Let’s talk about load balancing. The emergence of load balancing is to reduce the pressure on a single server as much as possible through horizontal expansion. Common WEB-level load balancing solutions include hardware F5, Nginx proxy, LVS, load balancing services of various cloud providers (such as AWS's ELB service), etc. What is connected behind the load balancing is usually the server that actually provides the service. For example, through the ELB service, the traffic can be evenly shared, thereby reducing the pressure on the stand-alone server. Since the load balancing layer has been added, simply using a certain solution still has to consider a single point of issue. The server responsible for load balancing failed to withstand the pressure, went down, and the service was unavailable. Therefore, Nginx and LVS try to configure multiple proxies to enable failover and fault alarm, so as to deal with proxy layer server problems in a timely manner. ELB is a service provided by Amazon. Its implementation has hundreds or even thousands of machines at the bottom, so just think of it as a proxy cluster. sharing: , assuming your site is stored on one machine, then this problem does not exist, because the session data is on this machine, but what if you use load balancing to distribute requests to different machines? At this time, there is no problem with the session ID in the client. However, assuming that the user's two requests go to two different machines, and its session data may exist in one of the machines, there will be a situation where the session data cannot be obtained. So session sharing becomes a problem 1. Session sharing based on NFS 2. Session sharing based on database 3. Session sharing based on Cookie 4. Session sharing based on cache (Memcache) 5. Session copy Global variables, local variables. zip, gzip, bzip2, tar Zcvf; varchar20How many Chinese characters can be stored? We must first determine the mysql version Below version 4.0, varchar(20) refers to 20 bytes. If UTF8 Chinese characters are stored, only 16 can be stored (each Chinese characters (3 bytes) Version 5.0 or above, varchar(20) refers to 20 characters, whether it is numbers, letters or UTF8 Chinese characters (each Chinese character is 3 bytes), 20 can be stored In fact, the best way is to create a table in your own database to try how many Chinese characters can be stored. Now that mysql 5.0 is available, varchar(20) can store 20 Chinese characters How to store the username and password when logging in: Usually we use cookies to store user information on the client, such as realizing a seven-day login-free system, etc. . We first set the cookie parameters when logging in and store the user name and password. Next time we jump to the next page, We can first determine whether there is a cookie If there is a value, it will jump directly to the next page. If there is no value, it will prompt you to log in. After implementing cookie storage, users can log in successfully without entering a password! Command to view the firewall: View the firewall status: service iptables status Turn on the firewall: service iptables start Turn off the firewall: service iptables stop Clustered index and non-clustered index Index: 1. Clustered index a) An index item directly corresponds to the storage page of the actual data record, which can be said to be "direct" b) The primary key is missing Save the use of it c) The sorting of index items is exactly the same as the storage sorting of data rows. Taking advantage of this, if you want to modify the storage order of data, you can change the primary key (cancel the original primary key and find another one). A field or a group of fields that can meet the requirements of the primary key, rebuild the primary key) d) A table can only have one clustered index (reason: once the data is stored, there can only be one order) 2、Non-clustered index a) It cannot be "directly accessed". It can only access multi-level page tables in a chain. Locate the data page b) A table can have multiple non-clustered indexes Single sign-on: 1. Description of the login principle Technical implementation mechanism of single sign-on: When the user accesses application system 1 for the first time, he will be directed to the authentication system because he has not yet logged in. Log in; Based on the login information provided by the user, the authentication system performs identity verification. If the verification is passed, an authentication credential - ticket should be returned to the user; when the user accesses other applications, he will bring this ticket with him as his own Authentication credentials. After the application system receives the request, it will send the ticket to the authentication system for verification to check the validity of the ticket. If the verification is passed, the user can access application system 2 and application system 3 without logging in again. It can be seen that to implement SSO, the following main functions are required: a) All application systems share an identity authentication system; b) All application systems can identify and extract ticket information; c) The application system can identify users who have logged in, and can automatically determine whether the current user has logged in, thereby completing the single sign-on function Based on the above basic principles, I designed a single sign-on system program using PHP language, and it has been put into operation to officially generate the server. This system program uses the ticket information with the unique session id of the entire system as a medium to obtain the current online user's entire site information (login status information and other user-wide site information that needs to be processed). Login process: 1. Log in to a site for the first time: a) The user enters the username + Password, send login request to the user verification center B) The current login site, through WebService request, user verification center verification user name, password legality. If the verification is passed, a ticket is generated to identify the user of the current session, and the site identifier of the currently logged in sub-site is recorded in the user center. Finally c) Return the obtained user data and ticket to the sub-site stand. If the verification fails, the corresponding error status code is returned. d) According to the result returned by the webservice request in the previous step, the current sub-site logs in the user: if the status code indicates success, the current site saves the ticket through the cookie of this site, and the site records the user's Login status. If the status code indicates failure, the user will be given a corresponding login failure prompt. 2. In the logged-in state, the user goes to another page: a) Verify the user's login status through the site's cookie or session: If the verification is passed, enter the normal site processing program; Otherwise, the user center verifies the user's login status (sends a ticket to the user verification center). If the verification is passed, local login processing is performed on the returned user information. Otherwise, it indicates that the user is not logged in. Logout process: a) The current logout site clears the user’s login status of the site and the locally saved user’s unique random ID b) Through the webservice interface, clear the unique random ID recorded in the entire site. The webservice interface will return, log out the javascript code of other logged-in sub-sites, and this site will output this code. c) js code accesses the W3C standard logout script of the corresponding site How to define class constants : Const What is an abstract method: A method without a method body is an abstract method. Use Keyword abstract to modify the data type of ajax, Parameters: 1 .json 2.jsonp 3.xml 4.html Three-level linkage: Subclass calls parent class ID Recursion Resolve primary key conflict Configuration file command #auto_increment_offset =1 #auto_increment_increment=2 5.Why use session control The http protocol is a stateless protocol that identifies users through session ID 6.What are the protocols httpHTTPS ip 7 HTTPWhat is the protocol Hypertext Transfer Protocol 8. What are XML and HTML; XML is Extensible Markup Language HTML is hypertext Markup language 9、What is jsonp One way to make cross-domain requests uses