search
HomeBackend DevelopmentPHP TutorialCollection of classic PHP interview questions_PHP tutorial

Collection of classic PHP interview questions

This article mainly introduces the collection of classic PHP interview questions. It collects and organizes common PHP interview questions and related reference answers for your reference. , friends in need can refer to it

This article analyzes classic PHP interview questions in more detail. Share it with everyone for your reference. The details are as follows:

I did some PHP questions on the Internet, and I have reached this point without realizing it...posting the answers for reference.

1. Use PHP to print out the time of the previous day in the format of 2006-5-10 22:21:21 (2 points)

?

1

2

$a = date("Y-m-d H:i:s", strtotime("-1 day"));

print_r($a);

1 2


$a = date("Y-m-d H:i:s", strtotime("-1 day"));

print_r($a);


2. The difference between echo(), print() and print_r() (3 points)

echo and print are not a function, but a language structure

int print(string $arg), only one parameter

echo arg1,arg2; can output multiple parameters and return void

1

2

$arr = array("key"=>"value");

print_r($arr);

echo and print can only print out strings, not structures print_r can print out the structure For example


?

1


2



$arr = array("key"=>"value");

print_r($arr);

1

2

3

4

5

6

7

8

9

10

11

12

function reverse($str)

{

$ret = "";

len=mbstrwidth(str,"GB2312");

for(i=0;i

{

arr[]=mbsubstr(str, $i, 1, "GB2312");

}

return implode("", array_reverse($arr));

}

print_r(reverse("你好"));

3. A template that allows HTML and PHP to be used separately (1 point) smarty,phplib

4. What tools are used for version control? (1 point)
svn,git,cvs

5. How to implement string flipping? (3 points)
English:
strrev($a)
Chinese or other text:

Chinese: GB2312, the code is encoded using GB2312



?

1

2

3

1

2

3

CURRENT_TIMESTAMP()

DATE_FORMAT()

select DATE_FORMAT("2011-11-21 10:10:10", "%Y-%m-%d");

4 5

6

7

8

1

mb_substr($str, 1, 1, "GB2312");

9 10 11 12
function reverse($str) { $ret = ""; len=mbstrwidth(str,"GB2312"); for(i=0;i { arr[]=mbsubstr(str, $i, 1, "GB2312"); } return implode("", array_reverse($arr)); } print_r(reverse("Hello"));
6. Methods to optimize MYSQL database. (4 points, write more and get more) In terms of sentences: 1 Use indexes to increase query efficiency 2 Optimize query statements and improve index hit rate Database involved: 1 Construct sub-databases and sub-tables to improve the storage and expansion capabilities of the database 2 Use different storage engines as needed 7. What does PHP mean (get 1 point) HyperText Preprocessing Language Hypertext PreProcessor 8. What is the function of MYSQL to obtain the current time?, and the function of formatting date is (2 points) ?
1 2 3 CURRENT_TIMESTAMP() DATE_FORMAT() select DATE_FORMAT("2011-11-21 10:10:10", "%Y-%m-%d");
9. A method to intercept Chinese text strings without garbled characters. (3 points) ?
1 mb_substr($str, 1, 1, "GB2312");

10. Have you ever used version control software? If so, what is the name of the version control software you used? (1 point)
svn
git

11. Have you ever used a template engine? If so, what is the name of the template engine you used? (1 point)
smarty

12. Please briefly describe your most proud development work (4 points)
XXX

13. For websites with high traffic, what methods do you use to solve the traffic problem? (4 points)
1 Use cache effectively to increase cache hit rate
2 Use load balancing
3 Use CDN to store and accelerate static files
4 ideas to reduce database usage
5 Check where the statistical bottlenecks are

14. Use PHP to write the code to display the client IP and server IP 1 point)
$_SERVER["REMOTE_ADDR"]
$_SERVER["SERVER_ADDR"]

15. What is the difference between the include and require statements? To avoid including the same file multiple times, you can replace them with (?) statements? (2 points)
On failure:
include generates a warning, while require generates an error interrupt
require is loaded before running
include is loaded at runtime
require_once
include_once

16. How to modify the survival time of SESSION (1 minute).
session_set_cookie_params

17. There is a web page address, such as the PHP Research Laboratory homepage: http://www.jb51.net/index.html, how to get its content? ($1 point)
file_get_contents
curl

18. In HTTP 1.0, the meaning of status code 401 is (?); if the prompt "File not found" is returned, the header function can be used, and its statement is (?); (2 points)
Unauthorized

?

1

header("HTTP/1.0 404 Not Found");

1
header("HTTP/1.0 404 Not Found");

fast CGI:

1

header("Status: 404 Not Found");

?


1

header("Status: 404 Not Found");

1

2

3

$a =

good test

EOD;

19. In PHP, heredoc is a special string, and its end mark must be? (1 point) Appear in pairs



?


1
2


3


$a =
good test

EOD;

20. Talk about the advantages and disadvantages of asp, php and jsp (1 point)

asp needs to rely on IIS and is a language developed by Microsoft

PHP and JSP can rely on other servers such as apache or nginx

1

2

3

$str = "jianfeng@126.com";

regex="([a−z0−9.−] )@([da−z.−] ).([a−z.]2,6)" ; //正则

return preg_match(regex,str)

21. Talk about your understanding of mvc (1 point) model: data structure layer view: show control: Receive and judge processing input 22. Write the SQL of the names of the ten people with the most posts, using the following table: members (id, username, posts, pass, email) (2 points) select top 10 id,username from members order by posts desc 23. 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? (2 points) & means passing a reference Passing parameters by reference in a function will change the parameters Generally, you can consider using references when there are multiple output parameters. 24. What is the function of error_reporting in PHP? (1 point) Set the display level of error 25. Please write a function to verify whether the format of the email is correct (2 points) ?
1 2 3 $str = "jianfeng@126.com"; regex="([a−z0−9.−] )@([da−z.−] ).([a−z.]2,6)" ; //Regular return preg_match(regex,str)

26. Briefly describe how to get the current execution script path, including the obtained parameters. (2 points)
$argc --Get the number of parameters
$argv --Get parameter list

27. How to modify the survival time of SESSION. (1 point)
session_set_cookie_params

28. What is the function to pop up a dialog box in a JS form? What is the function to get input focus? (2 points)

alert()
confirm()
promopt()
focus()

29. What is the redirection function of JS? How to introduce an external JS file? (2 points)

?

1

2

window.location.href="#"

1 2


window.location.href="#"

30. What is the difference between foo() and @foo()? (1 point)

1

2

3

class myclass

{

}

@ stands for all warnings and is ignored 31. How to declare a class named "myclass" without methods and attributes? (1 point)

?

1

1

$myclass = new myclass();

2 3

class myclass

{

}

1

2

3

4

5

6

7

8

class A

{

public $name = "A";

}

$a = new A();

n=a->name;

print_r($n);

32. How to instantiate an object named "myclass"? (1 point)

?

1

1

2

3

4

5

6

7

8

9

mysql_connect("localhost", "mysql_user", "mysql_password") or

die("Could not connect: " . mysql_error());

mysql_select_db("mydb");

$result = mysql_query("SELECT id, name FROM mytable");

while (row=mysqlfetcharray(result, MYSQL_ASSOC)) {

printf ("ID: %s Name: %s", row["id"],row["name"]);

}

mysql_free_result($result);

$myclass = new myclass();

33. How do you access and set the attributes of a class? (2 points)

?

1

2

3

4

echo "{html}"

echo

{html}

EOD;

1 2 3 4 5 6 7 8
class A { public $name = "A"; } $a = new A(); n=a->name; print_r($n);
34. What is the difference between mysql_fetch_row() and mysql_fetch_array? (1 point) mysql_fetch_array() is an extended version of mysql_fetch_row(). In addition to storing data in an array as a numerical index, you can also store data as an associative index, using the field name as the key. ?
1 2 3 4 5 6 7 8 9 mysql_connect("localhost", "mysql_user", "mysql_password") or die("Could not connect: " . mysql_error()); mysql_select_db("mydb"); $result = mysql_query("SELECT id, name FROM mytable"); while (row=mysqlfetcharray(result, MYSQL_ASSOC)) { printf ("ID: %s Name: %s", row["id"],row["name"]); } mysql_free_result($result);
35. What is the GD library used for? (1 point) Dynamic open image processing library 36. Point out some ways to enter a piece of HTML code in PHP. (1 point) ?
1 2 3 4 echo "{html}" echo {html} EOD;

37. Which of the following functions can open a file to read and write the file? (1 point) c
(a) fget() (b) file_open() (c) fopen() (d) open_file()

38. Which of the following options does not add john to the users array? (1 point) b
(a) $users[] = ‘john’;
(b) array_add($users,'john');
(c) array_push($users,‘john’);
(d) $users ||= ‘john’;

39. Will the following program be input? (1 point) 10

?

1

2

3

4

5

6

7

$num = 10;

function multiply(){

num=num * 10;

}

multiply();

echo $num;

?>

1 2

3

4

5

6

7

$num = 10;

1

2

3

4

5

6

7

8

9

10

11

12

$mysql_db=mysql_connect("local","root","pass");

@mysql_select_db("DB",$mysql_db);

$sql = sprintf("select * from %s where UserName = '%s'",

"表名",

"张三");

values=mysqlquery(sql);

while(item=mysqlfetchqueryarray(values))

{

echo sprintf("用户名:%s, 电话 %s, 学历: %s, 毕业日期: %s",

item['UserName'],item['Tel'], item['Content'],item['Date']

);

}

function multiply(){ num=num * 10;

}

multiply();

echo $num;

1

2

3

4

5

6

7

8

9

class test{

function Get_test($num){

num=md5(md5(num)."En");

return $num;

}

}

$test = new test();

ret=test->Get_test(11);

print_r($ret);exit;

?>
40. Use PHP to write a simple query to find out all the content named "Zhang San" and print it out (2 points) Table Name UserName Tel Content Date Zhang San 13333663366 Graduated from college 2006-10-11 Zhang San 13612312331 Bachelor degree 2006-10-15 Zhang Si 021-55665566 Graduated from technical secondary school 2006-10-15 Please complete the code according to the above question: ?
1 2 3 4 5 6 7 8 9 10 11 12 $mysql_db=mysql_connect("local","root","pass"); @mysql_select_db("DB",$mysql_db); $sql = sprintf("select * from %s where UserName = '%s'", "table name", "Zhang San"); values=mysqlquery(sql); while(item=mysqlfetchqueryarray(values)) { echo sprintf("Username: %s, phone number %s, education: %s, graduation date: %s", item['UserName'],item['Tel'], item['Content'],item['Date'] ); }
41. How to use the following classes and explain what they mean? (3) ?
1 2 3 4 5 6 7 8 9 class test{ function Get_test($num){ num=md5(md5(num)."En"); return $num; } } $test = new test(); ret=test->Get_test(11); print_r($ret);exit;

Associate the 32-bit string a1 generated after num is MD5 encoded with "En" and then perform MD5 encoding again

42. Write the format of SQL statements: insert, update, delete (4 points)
Table Name UserName Tel Content Date
Zhang San 13333663366 Graduated from college 2006-10-11
Zhang San 13612312331 Bachelor degree 2006-10-15
Zhang Si 021-55665566 Graduated from technical secondary school 2006-10-15
(a) There is a new record (Xiao Wang 13254748547 graduated from high school 2007-05-06). Please use SQL statements to add it to the table
insert into table name values('Xiao Wang', '13254748547', 'High School Graduation', '2007-05-06')
(b) Please use sql statement to update Zhang San’s time to the current system time
update table name set Date = GETDATE() where UserName = "Zhang San"
(c) Please write to delete all records named Zhang Si
delete from indicates where UserName = "张思"

43. Please write the meaning of data type (int char varchar datetime text); what is the difference between varchar and char (2 points)
int integer
char storage fixed length
varchar storage variable length
datetime time
text stores variable-length
varchar is variable length
char(20) fixed length

44. MySQ auto-increment type (usually table ID field) must be set to (?) field (1 point)
auto_increment
45. Write the output of the following program (1 point)

?

1

2

3

4

$b=201;

$c=40;

a=b>$c?4:5;

echo $a;

1 2

3

4

$b=201;

$c=40;

a=b>$c?4:5;

1

mysql_num_rows()

echo $a;

46. Is there a function that detects whether a variable is set? What is the function that detects whether it is empty? (2 points)

isset()

empty()

47. What is the function to obtain the total number of query result sets? (1 point)

1

2

3

4

print_r($arr[0]);

reset($arr);

print_r(current($arr));

print_r(array_shift($arr));

?

1

mysql_num_rows()

1

2

$a[0];

substr($a, 0, 1);

48. $arr = array('james', 'tom', 'symfony'); Please print out the value of the first element (1 point)



?

1

2

3

4

print_r($arr[0]);

reset($arr);

1

2

3

4

5

6

public function __construct()

{

}

public function __destruct()

{

}

print_r(current($arr)); print_r(array_shift($arr));
49. Please separate the array values ​​in question 41 with ',' signs and merge them into string output (1 point) implode 50. a='abcdef'; Please take out the value of a and print out the first letter (1 point) ?
1 2 $a[0]; substr($a, 0, 1);
51. Can PHP be connected to databases such as sql server/oracle? (1 point) Yes There are ready-made libraries 52. Please write the PHP5 permission control modifier (3 points) public private protected 53. Please write the constructor and destructor of php5 (2 points) ?
1 2 3 4 5 6 public function __construct() { } public function __destruct() { }

Programming questions:

1. Write a function to retrieve the file extension from a standard URL as efficiently as possible
For example: http://www.sina.com.cn/abc/de/fg.php?id=1 You need to remove php or .php

?

1

2

3

4

5

$url = "http://www.sina.com.cn/abc/de/fg.php?id=1";

arr=parseurl(url);

pathArr=pathinfo(arr['path']);

print_r($pathArr['extension']);

1 2

3

4

5

$url = "http://www.sina.com.cn/abc/de/fg.php?id=1";

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

$a = '/a/b/c/d/e.php';

$b = '/a/b/12/34/c.php';

//获取path相对于conpath的相对路径

function sGetRelativePath(path,conpath)

{

pathArr=explode("/",path);

conpathArr=explode("/",conpath);

$dismatchlen = 0;

for(i=0;i

{

if(conpathArr[i] != pathArr[i])

{

dismatchlen=count(pathArr) - $i;

arrLeft=arrayslice(pathArr, $i);

break;

}

}

ret=strrepeat("../",dismatchlen).implode("/", $arrLeft);

return $ret;

}

print_r(sGetRelativePath(b,a));

arr=parseurl(url); pathArr=pathinfo(arr['path']);

print_r($pathArr['extension']);

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

function aGetAllFile($folder)

{

$aFileArr = array();

if(is_dir($folder))

{

handle=opendir(folder);

while((file=readdir(handle)) !== false)

{

//如果是.或者..则跳过

if(file=="."||file == "..")

{

continue;

}

if(is_file(folder."/".file))

{

aFileArr[]=file;

}

else if(is_dir(folder."/".file))

{

aFileArr[file] = aGetAllFile(folder."/".file);

}

}

closedir($handle);

}

return $aFileArr;

}

$path = "/home/test/sql";

print_r(aGetAllFile($path));

3. 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'; Calculate the relative path of b relative to a should be http://www.jb51.net/12/34/c.php and add ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 $a = '/a/b/c/d/e.php'; $b = '/a/b/12/34/c.php'; //Get the relative path of path relative to conpath function sGetRelativePath(path,conpath) { pathArr=explode("/",path); conpathArr=explode("/",conpath); $dismatchlen = 0; for(i=0;i { if(conpathArr[i] != pathArr[i]) { dismatchlen=count(pathArr) - $i; arrLeft=arrayslice(pathArr, $i); break; } } ret=strrepeat("../",dismatchlen).implode("/", $arrLeft); return $ret; } print_r(sGetRelativePath(b,a));
3. Write a function that can traverse all files and subfolders in a folder. ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 function aGetAllFile($folder) { $aFileArr = array(); if(is_dir($folder)) { handle=opendir(folder); while((file=readdir(handle)) !== false) { //If yes.or..skip if(file=="."||file == "..") { continue; } if(is_file(folder."/".file)) { aFileArr[]=file; } else if(is_dir(folder."/".file)) { aFileArr[file] = aGetAllFile(folder."/".file); } } closedir($handle); } return $aFileArr; } $path = "/home/test/sql"; print_r(aGetAllFile($path));

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/970757.htmlTechArticleCollection of PHP classic interview questions This article mainly introduces the collection of classic PHP interview questions and collects and organizes common PHP interviews Questions and related reference answers are for your reference. Friends in need can refer to...
Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment