Home >Backend Development >PHP Tutorial >Summary of PHP interview questions
This article mainly introduces a summary of PHP interview questions, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
csrf What it is:
CSRF cross-site request forgery,
1. User C opens the browser, visits trusted website A, enters the username and password to 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. The user does not exit Before website A, open a TAB page in the same browser to access website B;
4. After website B receives the user request, it returns some offensive code and sends a request to access third-party site A. ;
5. After receiving these offensive codes, the browser carries the cookie information and sends a request to website A according to the request of website B without the user's knowledge. 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 executed
The difference between session and cookie:
1.COOKIE exists on the client side. SESSION exists on the server side.
2. The default storage size of COOKIE is 4kb. Generally, the number of COOKIES will not exceed 20, depending on the specific needs.
3.SESSION is stored in file mode by default. The default survival time is 24 minutes, the initial storage size is 1M, and it can be modified theoretically without limit. Can be configured by modifying php.ini.
4.SESSION is based on COOKIE by default. When SESSION is turned on, session_id will be generated and stored in COOKIE.
5.SESSION COOKIE are all session controls. Because our http is stateless and connectionless. So session control is needed to identify the user.
php Super global variables:
$GLOBALS $_SERVER $_REQUEST $_POST $_GET
PHP and MYSQL Transaction processing:
1. Use begin, rollback, and commit to implement begin 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: Transactions are the logical unit of work of the database, and they have Either all modifications are executed or none are executed. 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: After the transaction is completed, the changes made to the database by the transaction are persisted in the database and will not be rolled back.xss
How to prevent: XSS is also called CSS, the full name is CrossSiteScript, cross-site scripting attack
Prevent: script injection , escape filter script tags. The difference betweenunion
and unionall: union removes duplicates, unionall does not remove duplicates
RBAC
Role-based permission control: 5 tables User table, role table, function table, and tables related to each other: users and roles Tables, roles and functions tables
redis
Persistence: Memory snapshot (RDB) RDB persistence can be generated within a specified time interval Point-in-time snapshot of the data set
Log (AOF) AOF persistently records all write operation commands executed by the server, and restores the data set by re-executing these commands when the server starts.Sub-table:
Reduce the burden on the database and shorten query time.
Vertical table splitting: Vertical splitting is divided by fields.Horizontal table splitting: Put the data rows into two independent tables based on the values of one or more columns of 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.
jquerySelector:
1.Element 2.Attribute 3.id 4.Class 5.Global.
Inline elements and in-block elements
Inline: , ,
, ,
In block:
,
,
Conversion: display:inline,block,inline-block.
Difference:
block,
①Always starts on a new line and occupies a whole line;
②Height, line height, margins and inner margins The distance can be controlled;
③The bandwidth is always the same as the browser width, regardless of the 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 to solve the mismatch between object-oriented and relational databases
LinuxView port: Brush selected file: View process:
netstat-antu // View all current tcp ports ·
## netstat-ntulp | grep80 // . Situation·Linux
Check how many commands are executed: historyFile operation function:
open Open the file
fstat Get the file file Read the entire file into an array fclose Close the file fwrite Write to the file (safe to use Binary file) 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_substrmb_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, $encoding, The difference between #D and M
:
M instantiates the base class, and D can instantiate the custom class table
Interlaced color change: Use JQ to identify the even and odd numbers of table tr td, and assign different CSS styles to the corresponding odd and even numbers. Through different backgrounds, you can achieve interlaced color change. Effect. 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 operations After sending the request asynchronously, perform other operations directly without waiting for the return result from the server The default is: asynchronous Linux View all files: ls Set a p on another p: The larger the z-index value, the higher it goes. OB function: # OB_START (); // Open an output buffer, all output information will no longer be sent directly to the involved , but stored 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. ##3. How to make a shopping cart? process. . 1. First add a link on the page 1. Get the product id first 2. Display shopping cart items 2. You can modify the quantity of items in the shopping cart when clicking or -. 3. When the or-button is clicked, 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 ##redis and memecache is: SKUHow to do it: tp configuration file: common/config.php php data type: Singleton mode: Query the number of men and women between 20-30 Select count(*) from table name where age between 20 and 30 group by age. Group by PHP There are three access modifiers, namely: public (public, default) protected (protected) Access permission modification Scope of operators: private (private) protected (protected) protected is a little more complicated. Members declared as protected only allow access by subclasses of this class. mysql intStorage: bigint The 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. The 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. linuxCommands to view log file contents tail, cat, tac, head, echo tail-f test. LOG Top View memory # DF-LH View Disk PS-A View all processes ## constant: The difference is: The difference between methods and functions: Functions exist alone, while methods depend on the class and can only be called through objects. Value transfer and value reference: (1) By value Passing: Any changes to the value within the function scope will be ignored outside the function Prevent orders from being submitted repeatedly: 1. Use JS to disable the button after clicking it once. Using this method can prevent multiple clicks from happening String functions: strlen();strpos();echo();implode();trim(); etc.,, String reversal function: strrev, mb_string; The difference between http1.0 and http1.1: HTTP1.0 stipulates that 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. 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 was added to 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. Memory storage methods are different: global variables are stored in the global data area, and local variables are stored in the stack area 3. Lifecycles are different: the lifetime of global variables and the main The same as the program, it will be destroyed when the program is destroyed. Local variables are inside the function or inside the loop and will no longer exist when the function exits or the loop exits. 4. The usage is different: global variables are used in each part of the program after they are declared Parts can be used, 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 requests 2. Reduce DNS Search 3. Avoid redirects 4. Use Ajax caching 5. Lazy load 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 methods for Web components What is cache avalanche ? When the cache server is restarted or a large number of caches fail in a certain period of time, it will also put a lot of pressure on the back-end system (such as DB) when it fails. How to avoid it? 1: After the cache expires, control the number of threads that read the database and write the cache through locking or queuing. For example, only one thread is allowed to query data and write cache for a certain key, while other threads wait. 2: Set different expiration times for different keys to make the cache invalidation time points as even as possible. 3: Make a second-level cache, A1 is the original cache, A2 is the copy cache, when A1 fails, you can access A2, the cache expiration time of A1 is set to short-term, and A2 is set to long-term (this point is supplementary) tp Routing mode: 1. Normal mode 2. Rewrite mode 3. Compatibility mode niginxHow to configure the port number: Configure two servers in that nginx.conf, respectively The port number. jqGet the second row of the table tag: $(tr:eq(1)) What is a variable variable: Variable variables allow us to dynamically change the name of a variable. Use the value of one variable as the name of another 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: Generate two threads from the library, one I/O thread and one SQL thread; i/ The o thread requests the binlog of the main library and writes the obtained binlog log to the relay log (relay log) file; The main library will generate a log dump thread to provide i/o to the slave library The thread passes the binlog; The SQL thread will read the log in the relay log file and parse it into specific operations to achieve consistent master-slave operations and consistent data; Commands required for master-slave replication: showmaster status; startsalve; stopsalve; flushprivileges; GRANTREPLICATIONSLAVE,RELOAD,SUPER ON *.* TOmysql_backup@'%' IDENTIFIEDBY '123456'; CHANGEMASTER TOmaster_host = '127.0.0.1', ## ’s off ’s ‐‐ out‐over‐to‐under‐taken to .000001',master_log_pos = 3696; Create a master table, and the id is 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: (1 ) rr polling (default) It is assigned to each RS according to the request order. It is the same as the rr algorithm in lvs. If the RS is down, it will be automatically eliminated. By default, only port 80 is detected. If the RS reports 402, 403, 503, and 504 errors will be returned directly to the client. Minimum number of connections, whichever device has the fewest connections will be assigned to which 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 Server, go from 1 to N and then start 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 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; How many Chinese characters can be stored? First, you must determine the mysql version 4.0 Below, Varchar (20) refers to 20 bytes. If you store UTF8 Chinese characters, you can only save 16 (3 bytes of each Chinese character) 5.0 or more, Varchar (Varchar (Varchar (Varchar (Varchar (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 it in your own database. Let’s try how many Chinese characters can be put in a table. MySQL 5.0 is now available. Varchar(20) can store 20 Chinese characters. Username and password when logging in How to store: Generally, we use cookies to store user information on the client, such as a seven-day login-free system. 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 (before Centos7.0): 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: 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" # # # If there is a primary key, find another field or a group of fields that can also meet the requirements of the primary key, and 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) ) , non-clustered index a) It cannot be "directly accessed" and may access multiple objects in a chain The data page can be located only after leveling the page table b) A table can have multiple non-clustered indexes 1. Description of the login principle The technical implementation mechanism of single sign-on: When the user accesses application system 1 for the first time, because he has not logged in yet, he will be Guide to the authentication system to 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, this will be Bring the ticket as a credential for its own authentication. After receiving the request, the application system 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 officially put into operation to 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). 1. Log in to a site for the first time: a) The user enters the username and password , Send a login request to the user verification center b) Currently logged in to the site, through the webservice request, the user verification center verifies the legitimacy of the user name and password. 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, and finally c) Return the obtained user data and ticket to the sub-site. 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