Home > headlines > body text

Summary of common PHP interview questions (with answers)

Release: 2022-04-08 16:26:02
forward
79713 people have browsed it

This article summarizes some common PHP interview questions (with answers) for everyone. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Summary of common PHP interview questions (with answers)

# I remember the first time I interviewed for the PHP position. I just came out of school and didn’t know what the market was like, and it was zero. Experienced (insert here, zero experience, if you have never been involved in developing a complete or semi-finished project, the company will generally not want you, because the company recruits you because it wants you to help make things. To achieve the improvement of the company's business and performance). At that time, I just said that the trial period was 800 yuan. Of course, it was many years ago! It’s also a pretty low price, so the company just asked for it! ! ! The reason is very simple, everyone knows it!

[Related recommendations: php interview questions (summary)]

When doing projects in a company, growth is a process, and improving your own learning skills is a key The existing. Before entering the company, you will have one or two rounds of interviews and written tests. This is the case for everyone in our industry, so in addition to oral expression skills (being able to speak), there is also strength and ability. This is also what your interview questions require. embodied. There are many types of interview questions, but they are all inseparable from the basics of PHP. Some people who have just come out may not understand the test questions. Let me tell you a method, I actually used it at that time! Just memorize all the question types! The method is very old-fashioned and unrealistic. But it’s very useful, because I’ve encountered all the common question types~~Maybe I’m lucky!

Everyone may learn in their own way! I've been here like that before! Now, we still need to continue to learn and improve our skills, and keep learning as we go! Once you're in a trap, it's hard to get out!

The following recommends some common interview questions, I hope they are useful to you! !

1. Bubble sorting, be sure to remember it before the interview!

function maopao($arr)
{
    $len = count($arr);
    $n = count($arr) - 1;
    for ($i = 0; $i < $len; $i++) {
        for ($j = 0; $j < $n; $j++) {
            if ($arr[$j] > $arr[$j + 1]) {
                $tmp = $arr[$j];
                $arr[$j] = $arr[$j + 1];
                $arr[$j + 1] = $tmp;
            }
        }
    }
    return $arr;
}
Copy after login

2. Quick sort, be sure to remember it before the interview!

function quick_sort($array) {
    if (count($array) <= 1) return $array;
    $key = $array[0];
    $left_arr = array();
    $right_arr = array();
    for ($i=1; $i<count($array); $i++){
        if ($array[$i] <= $key)
            $left_arr[] = $array[$i];
        else
            $right_arr[] = $array[$i];
    }
    $left_arr = quick_sort($left_arr);
    $right_arr = quick_sort($right_arr);
    return array_merge($left_arr, array($key), $right_arr);
}
Copy after login

3. 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: function Any changes to the value within the scope 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

Advantages and disadvantages: By reference When a value is passed, php must copy the value. Especially for large strings and objects, this can be an expensive operation. Passing by reference does not require copying the value, which is good for improving performance. (The advantages and disadvantages will be tested)

4. What is the main difference between the field types varchar and char in the MySQL database?

Varchar is a variable Long, saving storage space, char is a fixed length. The search efficiency is faster than that of the char type, because varchar is a non-fixed length, and the length must be searched first, and then the data is extracted, which is one more step than the char fixed-length type, so the efficiency is lower.

5. Common storage engines of MySQL database and their differences?

MyISAM: Does not support transactions, table locks, is prone to fragmentation, must be optimized frequently, has fast read and write speeds, and supports full-text indexing.

InnoDB: supports transactions, row locks, and crash recovery capabilities. The reading and writing speed is slower than MyISAM, and full-text indexing is supported after 5.6.
The storage engine is based on tables, not databases

(This question can be more detailed if possible)

6. For websites with large traffic, what methods are used to solve the traffic problem?

First, confirm whether the server hardware is sufficient to support the current traffic

Secondly, optimize database access.

Third, prohibit external hotlinking.

Fourth, control the download of large files.

Fifth, use different hosts to divert the main traffic

Sixth, use traffic analysis and statistics software

Seventh, try to use static pages and cache

7. 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.

8. What is the difference between SESSION and COOKIE? This is the key point

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 can still be used. In the file that stores the session, the session ID is generated, and the session ID is passed to the page where the session is to be shared through get parameters, and the session ID is read to obtain data from the session.

It is recommended to look for detailed tutorials on session and cookies

9. Do you understand caching technology? redis is a test point

1. 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.

2. Use memcache for caching.

10. The difference between get and post submission methods in the form

get is explicit, and the data can be seen from the url and transmitted The amount of data is small and the security is low;

post is implicit, the amount of data transmitted is large and the security is high

11. Methods to optimize the database

Select the most applicable field attributes, reduce the width of the defined fields as much as possible, and try to set the fields to NOTNULL

Use connections (JOIN) instead of subqueries

Apply union (UNION) to replace manually created temporary tables

Transaction processing

Lock table, optimize transaction processing

Use foreign keys, optimize lock table

Use indexes

Optimize query statements

12. What is the difference between the statements include and require? What is the difference between the statements include and require?

require is an unconditional inclusion, that is, if require is added to a process, require will be executed first regardless of whether the condition is true. When the file does not exist or cannot be opened, an error will be prompted. And it will terminate the program execution

include has a return value, but require does not (maybe because require is faster than include). If the included file does not exist, an error will be prompted, but the program will Continue to execute

13. What is the difference between redis, memcacahe, and mongoDB?

They are all non-relational databases with very high performance, but mongoDB, memcache and redis are two different types. The latter two are mainly used for data caching. The former is mainly used for querying and storing big data. It is the document-type non-relational database closest to the database.

From the perspective of data storage location, memcache data is stored in memory, while redis can be stored in memory or on disk to achieve the function of persistent storage. Once memcache is powered off, the data If all is lost, redis can use snapshots and AOF to store the data to the disk. When recovering, it can read the data from the disk into the memory. When the physical memory is used up, the data can be written to the disk.

In terms of the type of data stored, memcache and redis store both key-value pairs, but redis values ​​have richer types, including string (string), hash (hash), list ( List), set (set) zset (ordered set), and memcache mainly stores strings.

14. Basic variable types of PHP

Four scalar types: boolean (Boolean type), integer (integer type), float ( Floating point type, also called double), string (string)

Two composite types: array (array), object (object)

Finally there are two special types: resource ( Resource), NULL (NULL)

15. How is staticization achieved? How to implement pseudo-static?

1. Staticization refers to page staticization, that is, generating real static files, that is, data can be obtained directly from files without querying the database. It's really static.
There are two main implementation methods:

One is the static file generated when we add information into the database, also known as template replacement technology.

One is that when the user accesses our page, he first determines whether a corresponding cache file exists. If there is a reading cache and there is no reading database, a cache file is generated at the same time.

2、伪静态不是真正意义上的静态化,之所以使用伪静态,主要是为了SEO推广,搜索引擎对动态的文件获取难度大,不利于网站的推广。实习原理是基于Apache或Nginx的rewrite机智
主要有两种方式:

一种是直接在配置虚拟机的位置配置伪静态,这个每次修改完成后需要重启web服务器。

另一种采用分布式的,可以在网站的根目录上创建.htaccess的文件,在里面配置相应的重写规则来实现伪静态,这种每次重写时不需要重启web服务器,且结构上比较清晰。

16、Mysql的读写分离?(进阶的会遇到)

读写分离的实现原理就是在执行SQL语句的时候,判断到底是读操作还是写操作,把读的操作转向到读服务器上(从服务器,一般是多台),写的操作转到写的服务器上(主服务器,一般是一台,视数据量来看)。当然为了保证多台数据库数据的一致性,需要主从复制。

17、如何处理负载,高并发?

1、HTML静态化
效率最高、消耗最小的就是纯静态化的html页面,所以我们尽可能使我们的 网站上的页面采用静态页面来实现,这个最简单的方法其实也是最有效的方法。
2、图片服务器分离
把图片单独存储,尽量减少图片等大流量的开销,可以放在一些相关的平台上,如七牛等
3、数据库集群和库表散列及缓存
数据库的并发连接为100,一台数据库远远不够,可以从读写分离、主从复制,数据库集群方面来着手。另外尽量减少数据库的访问,可以使用缓存数据库如memcache、redis。
4、镜像:
尽量减少下载,可以把不同的请求分发到多个镜像端。
5、负载均衡:
Apache的最大并发连接为1500,只能增加服务器,可以从硬件上着手,如F5服务器。当然硬件的成本比较高,我们往往从软件方面着手。

18、说一下单引号双引号?(基础考点)

单引号内部的变量不会执行, 双引号会执行

单引号解析速度比双引号快。

单引号只能解析部分特殊字符,双引号可以解析所有特殊字符。

19、PHP7的新特性?重点

标量类型声明:PHP 7 中的函数的形参类型声明可以是标量了。在 PHP 5 中只能是类名、接口、array 或者 callable (PHP 5.4,即可以是函数,包括匿名函数),现在也可以使用 string、int、float和 bool 了。

返回值类型声明:增加了对返回类型声明的支持。 类似于参数类型声明,返回类型声明指明了函数返回值的类型。可用的类型与参数声明中可用的类型相同。

NULL 合并运算符:由于日常使用中存在大量同时使用三元表达式和 isset()的情况,NULL 合并运算符使得变量存在且值不为NULL, 它就会返回自身的值,否则返回它的第二个操作数。

use 加强:从同一 namespace 导入的类、函数和常量现在可以通过单个 use 语句 一次性导入了

匿名类:现在支持通过new class 来实例化一个匿名类

20、PHP 数组排序

sort() - 以升序对数组排序

rsort() - 以降序对数组排序

asort() - 根据值,以升序对关联数组进行排序

ksort() - 根据键,以升序对关联数组进行排序

arsort() - 根据值,以降序对关联数组进行排序

krsort() - 根据键,以降序对关联数组进行排序

21、建立索引

(普通索引)->
创建:CREATE INDEX <索引名> ON tablename (索引字段)
修改:ALTER TABLE tablename ADD INDEX [索引名] (索引字段)
创表指定索引:CREATE TABLE tablename([...],INDEX[索引名](索引字段))
(唯一索引)->
创建:CREATE UNIQUE <索引名> ON tablename (索引字段)
修改:ALTER TABLE tablename ADD UNIQUE [索引名] (索引字段)
创表指定索引:CREATE TABLE tablename([...],UNIQUE[索引名](索引字段))
(主键)->
它是唯一索引,一般在创建表是建立,格式为:
CREATA TABLE tablename ([...],PRIMARY KEY[索引字段])
Copy after login

22、PHP支持多继承吗?

不支持。PHP中只允许单继承,父类可以被一个子类用关键字“extends”继承。

23、使用过Memcache缓存吗,如果使用过,能够简单的描述一下它的工作原理吗?

Memcahce是把所有的数据保存在内存当中,采用hash表的方式,每条数据又key和value组成,每个key是独一无二的,当要访问某个值的时候先按照找到值,然后返回结果。
Memcahce采用LRU算法来逐渐把过期数据清除掉。

24、优化MYSQL数据库的方法

(1)选择最有效率的表名顺序
(2)WHERE子句中的连接顺序
(3)SELECT子句中避免使用‘*’
(4)用Where子句替换HAVING子句
(5)通过内部函数提高SQL效率
(6)避免在索引列上使用计算。
(7)提高GROUP BY 语句的效率, 可以通过将不需要的记录在GROUP BY 之前过滤掉。

(1).选取最适用的字段属性,应该尽量把字段设置为NOT NULL
(2).使用连接(JOIN)来代替子查询(Sub-Queries)
(3).使用联合(UNION)来代替手动创建的临时表
(4).尽量少使用 LIKE 关键字和通配符
(5).使用事务和外键
Copy after login

25、MySQL主从备份的原理?

mysql支持单向、异步复制,复制过程中一个服务器充当主服务器,而一个或多个其它服务器充当从服务器。

26、error_reporting() 的作用?

设置 PHP 的报错级别并返回当前级别。

27、如何修改session的生存时间

在php.ini 中设置 session.gc_maxlifetime = 1440 //默认时间

代码实现

$lifeTime = 24 * 3600;  // 保存一天 
session_set_cookie_params($lifeTime); 
session_start();
Copy after login

28、常见的 PHP 安全性攻击

SQL注入:用户利用在表单字段输入SQL语句的方式来影响正常的SQL执行。
防止

使用mysql_real_escape_string()过滤数据

手动检查每一数据是否为正确的数据类型

使用预处理语句并绑定变量

参数化SQL:是指在设计与数据库链接并访问数据时,在需要填入数值或数据的地方,使用参数 (Parameter) 来给值,用@或?来表示参数。

XSS攻击 :跨站点脚本攻击,由用户输入一些数据到你的网站,其中包括客户端脚本(通常JavaScript)。如果你没有过滤就输出数据到另一个web页面,这个脚本将被执行。
防止:为了防止XSS攻击,使用PHP的htmlentities()函数过滤再输出到浏览器。

CSRF: Cross-site request forgery refers to a request made by a page that looks like a trusted user of the website, but is fake
Prevention: General In other words, make sure the user comes from your form and matches every form you send out. There are two points that must be remembered:

Use appropriate security measures for user sessions, such as updating IDs for each session and using SSL for users.

Generate another one-time token and embed it into the form, save it in the session (a session variable), and check it on submit. For example, _token

code injection in laravel: Code injection is caused by exploiting computer vulnerabilities by processing invalid data. The problem comes when you accidentally execute arbitrary code, usually via file inclusion. Poorly written code can allow a remote file to be included and executed. Like many PHP functions, require can contain a URL or file name.
Prevent code injection

Filter user input

Set disable allow_url_fopen and allow_url_include in php.ini. This will disable the remote files of require/include/fopen

There are many types of questions. I hope you will slowly discover and slowly improve your learning skills during the learning process. Finally, I wish you all a happy study. ! !

Related labels:
source:php自学中心
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