Home>Article>Backend Development> [Hematemesis Compilation] 40+ PHP interview questions with answers (practical experience)
This article summarizes 40 PHP interview questions and answers for you. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#1. What is object-oriented? What are the main features?
Object-oriented is a design method for programs, which helps improve the reusability of programs and makes the program structure clearer. Main features: encapsulation, inheritance, polymorphism.
2. What is the difference between SESSION and COOKIE? Please explain the reasons and functions from the protocol?
A. http is stateless The protocol cannot distinguish whether users come from the same website. The same user requesting different pages cannot be regarded as the same user.
B. SESSION is stored on the server side, and COOKIE is stored on the client side. Session is relatively secure. Cookies can be modified by certain means and are not safe. Session relies on cookies for delivery.
After disabling cookies, the session cannot be used normally. Disadvantages of Session: It is saved on the server side, and each read is read from the server, which consumes resources on the server. Session is saved in a file or database on the server side. It is saved in a file by default. The file path is specified by session.save_path in the PHP configuration file. Session files are public.
3. What are the meanings of 302, 403, and 500 codes in HTTP status?
Principle of one, two, three, four and five: (i.e. one: message series; two: success series; three: redirection series; four: request error series; five: server-side error series. )
302: Temporary transfer successful, the requested content has been moved to the new location
403: Access prohibited
500: Internal server error
401: Represents unauthorized access.
4. Please write down the meaning of the data type (int char varchar datetime text); what is the difference between varchar and char?
Int Integer char Fixed-length character Varchar Variable-length character Datetime Date and time type Text The difference between text type Varchar and char char is a fixed-length character type, and it takes up as much space as it allocates. space. Varchar is a variable-length character type. It takes up as much space as the content is, which can effectively save space. Since the varchar type is variable, the server has to perform additional operations when the data length changes, so the efficiency is lower than that of the char type.
5. What are the basic differences between MyISAM and InnoDB? How is the index structure implemented?
A. The MyISAM type does not support transactions, table locks, and is prone to fragmentation. It needs to be optimized frequently and has fast read and write speeds. It is suitable for applications with frequent queries;
B. The InnoDB type supports transactions, row locks, and has crash recovery capabilities. The read and write speed is slower than MyISAM. It is suitable for applications with a lot of insert and update operations. It takes up a lot of space and does not support full-text indexes.
Create index: alert table tablename add index index name (`field name`)
6, difference between isset() and empty()
sset determines whether a variable exists. Multiple variables can be passed in. If one of the variables does not exist, it will return false; empty determines whether the variable is empty and it will be false. Only one variable can be passed. If it is empty, it will return true.
https://jq.qq.com/?_wv=1027&k=55dPDrC
7. Please explain the difference between passing by value and passing by reference in PHP. When to pass by value and when to pass by reference?
Pass by value: Any changes to the value within the scope of the function will be ignored outside the function
By reference Passing: Any changes to the value within the function scope will also reflect these modifications outside the function
Advantages and Disadvantages: When passing by value, PHP must copy the value. Especially for large strings and objects, this can be a costly operation. Passing by reference does not require copying the value, which is good for improving performance.
8. What is the function of error_reporting in PHP?
Set the error level of PHP and return the current level.
9. Tell me about your understanding of caching technology?
Caching technology is to cache dynamic content into files, and access dynamic pages within a certain period of time to directly call the cached files without having to revisit the database.
10. Nowadays, MVC three-layer structure is often used in programming. Which three layers does MVC refer to and what are its advantages?
The three layers of MVC refer to: business model, view, and controller respectively. The controller layer calls the model to process the data, and then maps the data to the view layer for display. The advantages are: ① It can Achieve code reusability and avoid code redundancy; ②M and V realize code separation, so that the same program can use different expressions
11. What are the advantages of AJAX ?
ajax is an asynchronous transmission technology that can be implemented through javascript or the JQuery framework to achieve partial refresh, which reduces the pressure on the server and improves the user experience.
12. In the development of the program, how to improve the operating efficiency of the program?
A. Optimize SQL statements. Try not to use select * in query statements. Use which field to check which field; use less subqueries and can be replaced by table connections; use less fuzzy queries;
B. Create an index in the data table;
C. Generate cache for data frequently used in the program.
13. For websites with large traffic, what methods do you use to solve the traffic problem?
A. Use cache effectively. Increase cache hit rate
B, use load balancing
C, use cdn to store and accelerate static files
D, ideas to reduce database usage
E. Check where the bottleneck of statistics is
F. Reverse proxy
14. What is the difference between the statement include and require? In order to avoid including the same statement multiple times files, what statements can be used to replace them?
Difference:
When it fails:
include generates a warning, And require generates an error interrupt directly
require is loaded before running
include is loaded at runtime
Replace:
require_once
15. What is the difference between foo() and @foo()?
@ represents all warnings and is ignored16. Brief description PHP's garbage collection mechanism.
Answer: Variables in php are stored in the variable container zval. In addition to storing variable types and values, zval also has is_ref and refcount fields. refcount indicates the number of elements pointing to the variable, and is_ref indicates whether the variable has an alias. If refcount is 0, the variable container is recycled. If a zval's refcount is greater than 0 after being reduced by 1, it will enter the garbage buffer. When the buffer reaches the maximum value, the recycling algorithm will loop through the zval to determine whether it is garbage and release it.17. How to maximize the security of PHP? How to avoid SQL injection vulnerabilities and XSS cross-site scripting vulnerabilities?
Answer: Basic principles: Do not show server or program design details to the outside world (masking errors), do not trust any user-submitted data (filter user submissions).18. Differences between echo, print_r, print, and var_dump
19. Features of writing smarty template
Fast speed and compilation type , caching technology, plug-in mechanism, powerful performance logic20. How to implement page jump in PHP
Method 1: PHP function jump , Disadvantage, there cannot be output before the header, the program after the jump continues to execute, and exit can be used to interrupt the execution of the subsequent program.header("Location:网址");//直接跳转 header("refresh:3;url=http://www.jsdaima.com");//三秒后跳转Method 2: Using meta
echo"";
21. How to convert a string in GB2312 format into UTF-8 format?
iconv('GB2312','UTF-8','js代码(http://www.jsdaima.com)是IT资源下载与IT技能学习平台。');
22. If the content input by the user needs to be output as it is, which function should be used to process the data before entering it into the database?
htmlspecialchars or htmlentities23. What is a CSRF attack? XSS attack? How to prevent it?
CSRF, cross-site request forgery, the attacker pretends to be a user and sends a request to steal information or damage the system. Describe the basic principle: the user visits website A to log in and generates a cookie, and then visits website B. If website A has a CSRF vulnerability, website B's request to website A (this is equivalent to a user visit), Website A will think that the request is from a user, so website B successfully disguises your identity, so it is called a cross-site scripting attack. CSRF prevention: A. Reasonably standardize the api request method, GET, POST B. Add token verification to the POST request, generate a random code and save it session, bring this random code to the form, and when submitting, the server will verify whether the random code is the same. XSS, cross-site scripting attack. Prevention: Do not trust any input, filter input.#24. Security is crucial to a program. Please tell us what security mechanisms should be paid attention to during development?
A. Prevent remote submission;B. Prevent SQL injection and filter special codes;
C. Prevent registration machine flooding and use verification codes.
25. Do you understand the json data format?
JSON (javascript object Notation) is a lightweight data exchange format. The json data format is fixed and can be used for data transfer in multiple languages.
26. What is a transaction? and its characteristics?
Answer: Transaction: It is a series of database operations and the basic logical unit of database applications.
Transaction characteristics:
A. Atomicity: that is, indivisibility. Either all transactions are executed or none are executed.
B. Consistency or stringability. The execution of a transaction converts the database from one correct state to another correct state
C. Isolation. Before the transaction is correctly committed, any changes to the data by the transaction are not allowed to be provided to any other transaction,
D. Durability. After a transaction is submitted correctly, its results will be permanently saved in the database. Even if there are other failures after the transaction is submitted, the processing results of the transaction will be saved.
Or understand it this way:
A transaction is a group of SQL statements that are bound together as a logical unit of work. If any statement operation fails, the entire operation will fail, and subsequent operations will Roll back to the state before the operation, or there is a node on it. To ensure that something is either executed or not executed, transactions can be used. For a grouped statement to be considered a transaction, it needs to pass the ACID tests, namely atomicity, consistency, isolation, and durability.
27. What is a lock?
Answer: The database is a shared resource used by multiple users. When multiple users access data concurrently, multiple transactions simultaneously access the same data in the database. If concurrent operations are not controlled, incorrect data may be read and stored, destroying the consistency of the database.
Locking is a very important technology to achieve database concurrency control. Before a transaction operates on a data object, it first sends a request to the system to lock it. After locking, the transaction has certain control over the data object. Before the transaction releases the lock, other transactions cannot update the data object.
Basic lock types: locks include row-level locks and table-level locks
28. What is the role of indexes? And what are its advantages and disadvantages?
Answer: An index is a special query table that the database search engine can use to speed up data retrieval. It is very similar to the table of contents of a book in real life. You can find the data you want without querying the entire book. Indexes can be unique. Creating an index allows you to specify a single column or multiple columns. The disadvantage is that it slows down data entry and increases the size of the database.
29. How to understand the three paradigms in a popular way?
First normal form: 1NF is an atomic constraint on attributes, which requires attributes to be atomic and cannot be decomposed;
Second normal form: 2NF is a unique constraint on records , requiring records to have unique identifiers, that is, the uniqueness of entities;
Third normal form: 3NF is a constraint on field redundancy, that is, any field cannot be derived from other fields, and it requires that fields are not redundant.
30. What is the difference between primary key, foreign key and index?
Definition:
Primary key--uniquely identifies a record, cannot be duplicated, and is not allowed to be empty
Foreign key--the foreign key of a table belongs to another table Primary key, foreign key can have duplicates, can be empty value
Index--This field has no repeated values, but can have a null value
Function:
Primary key--used to ensure data integrity Property
Foreign key--used to establish connections with other tables
Index--to improve the speed of query sorting
Number:
Primary key--there can only be one primary key
Foreign key--a table can have multiple foreign keys
Index--a table can have multiple unique indexes
31. Brief description of private, protected, public modifications access rights.
private: Private members can only be accessed inside the class.
protected: Protected members can be accessed within the class and inherited classes.
public: Public members, completely public, no access restrictions.
32. What is the difference between heap and stack?
A. The heap is the memory space dynamically allocated during the running of the program. You can determine the size of the heap memory to be allocated according to the running conditions of the program;
B. The stack is the memory space allocated during compilation. It is the allocated memory space, so the size of the stack must be clearly defined in your code.
33. What are the commonly used magic methods? Example
Answer: PHP stipulates that methods starting with two underscores (__) are reserved as magic methods, so it is recommended that your function name should not start with __ unless it is for redundancy. Contains existing magic methods.
__construct() 实例化类时自动调用。
__destruct() 类对象使用结束时自动调用。
__set() 在给未定义的属性赋值的时候调用。
__get() 调用未定义的属性时候调用。
__isset() 使用isset()或empty()函数时候会调用。
__unset() 使用unset()时候会调用。
__sleep() 使用serialize序列化时候调用。
__wakeup() 使用unserialize反序列化的时候调用。
__call() 调用一个不存在的方法的时候调用。
__callStatic()调用一个不存在的静态方法是调用。
__toString() 把对象转换成字符串的时候会调用。比如 echo。
__invoke() 当尝试把对象当方法调用时调用。
__set_state() 当使用var_export()函数时候调用。接受一个数组参数。
__clone() 当使用clone复制一个对象时候调用。
34、$this和self、parent这三个关键词分别代表什么?在哪些场合下使用?
$this 当前对象
self 当前类
parent 当前类的父类
$this在当前类中使用,使用->调用属性和方法
self也在当前类中使用,不过需要使用::调用
parent在类中使用
35、作用域操作符::如何使用?都在哪些场合下使用?
调用类常量
调用静态方法
36、__autoload()方法的工作原理是什么?
答:使用这个魔术函数的基本条件是类文件的文件名要和类的名字保持一致。
当程序执行到实例化某个类的时候,如果在实例化前没有引入这个类文件,那么就自动执行__autoload()函数。
这个函数会根据实例化的类的名称来查找这个类文件的路径,当判断这个类文件路径下确实存在这个类文件后
就执行include或者require来载入该类,然后程序继续执行,如果这个路径下不存在该文件时就提示错误。
使用自动载入的魔术函数可以不必要写很多个include或者require函数。
37、简述高并发网站解决方案。
A、前端优化(CND加速、建立独立图片服务器)
B、服务端优化(页面静态化、并发处理[异步|多线程]、队列处理)
C、数据库优化(数据库缓存[Memcachaed|Redis]、读写分离、分库分表、分区)
D、Web服务器优化(负载均衡、反向代理)
38、PHP遍历文件夹下所有文件
e4ef26a3c0542c88b61633ff44decbe4'; read_all($temp); }else{ if($fl !='.' && $fl != '..'){ echo '文件:'.$temp.'0c6dc11e160d3b678d68754cc175188a'; } } } } } read_all("./dir/"); ?>
39、在命令行中运行php程序
php indx.php
A、从命令行运行php非常简单。但有些注意事项需要各位了解下,诸如$_SESSION之类的服务器变量是无法在命令行中使用的,其他代码的运行则和web服务器中完全一样;
B、在命令行中执行php文件的好处之一就是可以通过脚本实现一些计划任务(crontab)的执行,而无须通过web服务器。
延伸1:
php -v 显示当前PHP版本
php -m 显示当前php加载的有效模块
php -i 输出无html格式的phpinfo
php --rf function
延伸2:向php脚本传递参数:
提示:命令行下执行php,是不走Apache/Nginx等这类东西的,没有什么http协议,所以get,post传参数根本不起作用,并且还会报错。有些时候需要在shell命令下把PHP当作脚本执行,比如定时任务。这就涉及到在shell命令下如何给php传参的问题,通常有三种方式传参。
A、使用$argv or $argc参数接收
echo "接收到{$argc}个参数"; print_r($argv);
B、使用getopt函数
$param_arr = getopt('a:b:'); print_r($param_arr);
C、提示用户输入
fwrite(STDOUT,'Please enter your name:'); echo 'Your name is:'.fgets(STDIN);
40、你用什么方法检查PHP脚本的执行效率(通常是脚本执行时间)和数据库SQL的效率(通常是数据库Query时间),并定位和分析脚本执行和数据库查询的瓶颈所在?
A、PHP脚本的执行效率
a、代码脚本里计时;
b、xdebug统计函数执行次数和具体时间进行分析,最好使用工具winCacheGrind分析;
c、在线系统用strace跟踪相关进程的具体系统调用。
B、数据库SQL的效率
a、sql的explain(mysql),启用slow query log记录慢查询;
b、通常还要看数据库设计是否合理,需求是否合理等。
41、对于大流量的网站,您采用什么样的方法来解决各页面访问量统计问题。
A. Confirm whether the server can support the current traffic;
B. Optimize database access;
C. Prohibit external access links (hotlinking), such as anti-hotlinking for pictures;
D. Control file downloads , especially large files;
E. Use different hosts for offloading (load balancing);
F. Use browsing statistics software to understand the number of visits and perform targeted optimization.
42. The MySQL database is used as the storage of the publishing system. The increment of more than 50,000 items per day is expected to last three years. How to optimize it?
A. Design a well-designed database structure, allow partial data redundancy, and try to avoid join queries to improve efficiency;
B. Choose appropriate table field data types and storage engines, Appropriately add indexes;
C. Separate master-slave reading and writing in the mysql database;
D. Find regular tables to reduce the amount of data in a single table and improve query speed;
E. Add a caching mechanism, such as memcached , redis, etc.;
F. Generate static pages for pages that do not change frequently;
G. Write efficient SQL. For example, SELECT * FROM TABEL is changed to SELECT field_1, field_2, field_3 FROM TABLE.
43. Mysql storage engine, the difference between myisam and innodb.
A. The MyISAM type does not support advanced processing such as transaction processing, but the InnoDB type does;
B. The MyISAM type table emphasizes performance, and its execution speed is higher than InnoDB type is faster;
C. InnoDB does not support FULLTEXT type index;
D. InnoDB does not save the specific number of rows in the table, that is, execute select count(*) from table, InnoDB has to scan the entire table to calculate how many rows there are, but MyISAM simply reads the number of saved rows;
E. For fields of the AUTO_INCREMENT type, InnoDB must contain only the number of rows. The index of the field, but in the MyISAM table, a joint index can be established together with other fields;
F. When DELETE FROM table, InnoDB will not re-create the table, but will delete it row by row;
G. The LOAD TABLE FROM MASTER operation does not work for InnoDB. The solution is to first change the InnoDB table to a MyISAM table, and then change it to an InnoDB table after importing the data. However, for the additional InnoDB features (such as foreign keys) ) tables are not applicable;
H, MyISAM supports table locks, and InnoDB supports row locks.
MyISAM: Mature, stable, easy to manage, fast to read. Some functions do not support (transactions, etc.), table-level locks.
InnoDB: supports transactions, foreign keys and other features, and data row locking. It takes up a lot of space and does not support full-text indexing, etc.
Others, mainly some personal opinions and metaphysics after the interview:
1. Many working students feel that asking for leave for interviews Trouble, in fact, many companies now arrange evening interviews and special weekend interviews. Just communicate with them in advance. If you ask for leave, it shouldn't be a problem to interview three companies in one day.
2. The order of delivery companies is recommended. First, warm up with one or two companies, then compare the companies that you are confident about, then the companies that you are very interested in, and finally the selective interview. The main reason for arranging this order is that although you may be very good at your business, entering the interview state requires a process. It is necessary to warm up for the interview. By the way, I would like to emphasize that preparing for the interview in advance, such as reading the interview questions and reviewing technical books, are very useful. necessary. The main reason for choosing a reliable company that you like in advance is to get an offer, firstly to verify your self-worth, and secondly to feel confident.
3. Adjust your mentality. In fact, some offers are based on luck. After all, for some large companies, interviews are common but recruitment is not common, so don’t be discouraged if you can’t get an offer.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of [Hematemesis Compilation] 40+ PHP interview questions with answers (practical experience). For more information, please follow other related articles on the PHP Chinese website!