PHP interview question: PS this interview question is difficult. Welcome to leave a comment on the challenge.

Time:2022-5-7

###

  1. Write a PHP function that can create multi-level directories

<? PHP / * * * create multi-level directory * @ param $path string directory to be created * @ param $mode int create directory mode, which can be ignored under windows*/

function create_ Dir ($path, $mode = 0777) {if (is_dir ($path)) {# if the directory already exists, do not create echo “the directory already exists”;} else {

#If it doesn’t exist, create if (MKDIR ($path, $mode, true)) {echo “directory creation succeeded”;} else {

Echo “failed to create directory”;}}}

?>

###

  1. Write out the characteristics of Smarty template

Fast, compiled, cache technology, plug-in mechanism, powerful presentation logic

###

  1. Open PHP Safe in ini_ Mode, which functions will be affected? Say at least six.

safe_ Mode, PHP security mode, which provides a basically secure shared environment on a PHP developed web server with multiple user accounts. When safe mode is turned on, some functions will be completely disabled, while the functions of other functions will be limited, such as chdir and move_ uploaded_ file,chgrp,parse_ ini_ File, chown, rmdir, copy, rename, fopen, require, MKDIR, unlink, etc. Note that at PHP5 Version above 3, safe_ Mode is deprecated at PHP5 4 or above, this feature is completely removed.

###

  1. What function would you use to grab remote images to the local?

file_ get_ Contents or curl

###

5. What is the garbage collection mechanism of PHP

PHP can automatically manage memory and clear objects that are no longer needed. PHP uses the simple garbage collection mechanism of reference counting. Each object contains a reference counter. Each reference is connected to the object, and the counter is incremented by 1. When the reference leaves the living space or is set to null, the counter is decremented by 1. When the reference counter of an object is zero, PHP knows that you will no longer need to use this object to free up its memory space.

###

  1. Please write a piece of PHP code to ensure that multiple processes write to the same file successfully at the same time

Core idea: lock

<? php $fp = fopen (“lock.txt”,”w+”); If (flock ($FP, lock_ex)) {/ / obtain write lock and write data fwrite ($FP, “write something”); / / unlock flock ($FP, lock_un);

} else {

echo “file is locking…”; }

fclose($fp);

?>

###

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

<?php

//Scheme 1 function getext1 ($URL){

$arr = parse_url($url); //Array ( [scheme] => http [host] => www.sina.com.cn [path] => /abc/de/fg.php [query] => id=1 )

$file = basename($arr[‘path’]); $ext = explode(‘.’, $file); return $ext[count($ext)-1]; }

//Scheme 2 function getext2 ($URL){

$url = basename($url); $pos1 = strpos($url,’.’); $pos2 = strpos($url,’?’);

if (strstr($url,’?’)) { return substr($url,$pos1+1,$pos2-$pos1-1);

} else { return substr($url,$pos1); } }

$path = “http://www.sina.com.cn/abc/de/fg.php?id=1″; echo getExt1($path); echo ”
“; echo getExt2($path);

?>

Related topics: use more than five ways to obtain the extension of a file. Requirements: dir / upload image. Jpg, find out Jpg or JPG must be processed with PHP’s own processing function. The method cannot be obviously repeated. It can be encapsulated into a function, such as get_ ext1 (file_name)

###

  1. Write a function that can traverse all files and subfolders under a folder.

<?php

function my_scandir($dir){ $files = array(); if(is_dir($dir)){ if ($handle = opendir($dir)) { while (($flie = readdir($handle))!== false) { if ($flie!=”.” && $file!=”..”) { if (is_dir($dir.”/”.$file)) { $files[$file] = my_scandir($dir.”/”.$file);

} else { $files[] = $dir.”/”.$file;

}

}

}

closedir($handle); return $files; } } }

?>

###

  1. This paper briefly describes the implementation principle of infinite classification in the forum.

Create a category table as follows:

CREATE TABLE category(

cat_ id smallint unsigned not null auto_ ‘primary ID’ remark ‘,
cat_ Name varchar (30) not null default ” comment ‘category name’,
parent_ ID smallint unsigned not null default 0 comment ‘category parent ID’
)engine=MyISAM charset=utf8;

Write a function, recursive traversal, to achieve infinite classification

<? PHP function tree ($arr, $PID = 0, $level = 0) {static $list = array(); foreach ($arr as $V) {/ / if it is a top-level classification, save it to $list and use this node as the root node to traverse its child nodes if ($V [‘parent_id ‘] = $PID) {$v [‘level’] = $level; $list [] = $V; tree ($arr, $v [‘cat_id ‘], $level + 1);}}

return $list; }

?>

###

  1. Write a function to calculate the relative path of two files, such as B = ‘/ A / B / 12 / 34 / c.php’; The calculated relative path of a should be.. // c/d

<?php function releative_path($path1,$path2){ $arr1 = explode(“/”,dirname($path1)); $arr2 = explode(“/”,dirname($path2));

for ($i=0,$len = count($arr2); $i < $len; $i++) { if ($arr1[$i]!=$arr2[$i]) { break; } }

//Not in the same root directory if ($I = = 1) {$return_path = array();}

//In the same root directory, if ($I! = 1 & & $I < $len) {$return_path = array_fill (0, $len – $I, “..);}

//In the same directory, if ($I = = $len) {$return_path = array (‘. /’);}

$return_path = array_merge($return_path,array_slice($arr1,$i)); return implode(‘/’,$return_path);

}

$a = ‘/a/b/c/d/e.php’; $b = ‘/a/b/12/34/c.php’; $c = ‘/e/b/c/d/f.php’; $d = ‘/a/b/c/d/g.php’;

echo releative_ path ($a,$b);// The result is.. // c/d echo “

?>

###

11.mysql_ fetch_ Row () and MySQL_ fetch_ What’s the difference between array()?

mysql_ fetch_ Row () stores a column of the database in a zero based array. The first column is at index 0 of the array, the second column is at index 1, and so on.

mysql_ fetch_ Assoc () stores a column of the database in an associative array. The index of the array is the field name. For example, my database query returns three fields: “first_name”, “last_name” and “email”. The index of the array is “first_name”, “last_name” and “email”.

mysql_ fetch_ Array () can send back MySQL at the same time_ fetch_ Row () and MySQL_ fetch_ The value of assoc().

###

  1. There is a web page address, such as the homepage of PHP development resources network:www.phpres.com/index.html, how to get its content?

Method 1 (for PHP5 and later):

$readcontents=fopen(“http://www.phpres.com/index.html”,”rb”);
$contents=stream_get_contents($readcontents);
fclose($readcontents);
echo $contents;

Method 2:

echo file_get_contents(“http://www.phpres.com/index.html”);

###

  1. On the understanding of MVC

Application program completed by model, view and controller. The model layer is responsible for providing data, and all operations related to the database are handed over to the model layer for processing. The view layer provides an interactive interface and outputs data, while the controller layer is responsible for receiving requests, distributing them to the corresponding model for processing, and then calling the view layer for display.

###

14.What does the GD library do?

GD library provides a series of APIs for processing pictures. Using GD library, you can process pictures or generate pictures. On the website, Gd library is usually used to generate thumbnails, watermark pictures or generate reports on website data. Since PHP version 4.3.0, Gd has been built into the PHP system.

###

15.What function can you use to open a file for reading and writing?

A.fget (); B.file_ open (); C.fopen (); D.open_ file (); Answer: C fget() this is not a PHP function and will cause execution errors. file_ Open() this is not a PHP function and will cause an execution error. Fopen() this is the correct answer. Fopen() can be used to open files for reading and writing. open_ File() is not a PHP function and will cause execution errors.

###

16. Principle of Smarty

Smarty is a template engine. The main purpose of using Smarty is to realize the separation of logic and external content. If you don’t use templates, the usual practice is to mix PHP code and HTML code. After using the template, you can put the business logic into the PHP file, and the template responsible for displaying the content into the HTML file.

When Smarty executes the display method, it reads the template file, replaces the data, and generates the compiled file. After each access, it will directly access the compiled file. Reading the compiled file saves the time of reading the template file and string replacement, so it can be faster. The time stamp in the compiled file records the modification time of the template file. If the template is modified, it can be detected, Then recompile (compilation is to save the static content, and the dynamic content varies according to the incoming parameters).

If caching is enabled, the cache file will be generated according to the compiled file. When accessing, if there is a cache file and the cache file has not expired, the cache file will be accessed directly.

Related topic 1: templates that can separate HTML and PHP

Smarty, phplib, etc

Related topic 2: have you ever used a template engine? If yes, what is the name of the template engine you use?

Smarty

###

17. How to realize page Jump in PHP

Method 1: PHP function jump. Disadvantages: there can be no output before the header. The program after jump continues to execute, and the following program can be executed with exit interrupt.

Header (“location: Web address”)// Direct jump
header(“refresh:3;url=http://axgle.za.NET”);//Jump in three seconds

Method 2: using meta

echo”“;

###

18. Can PHP connect to databases such as SQL Server / oracle?

sure

###

  1. What tools are used for version control?

Svn or CVs, GIT

Related topic: have you ever used version control software? If yes, what is the name of the version control software you use?

TortoiseSVN-1.2.6

###

  1. Write a regular expression to consider all JS / VBS scripts on the web page (that is, remove the script tag and its content):

Filter JavaScript script References:

<?php

header(“content-type:text/html;charset=utf-8”);

$script = “the following is not displayed:”;

$pattern = ‘//si’;

echo preg_ Replace ($pattern, “script content”, $script)// The following are not displayed: script content

###

21.Given a line of text $string,how would you write a regular expression to strip all the HTML tags from it?

Scheme 1: use PHP built-in function strip_ Tags() removes the HTML tag scheme 2, and the user-defined function is as follows:

<?php

header(“content-type:text/html;charset=utf-8”);

function strip_html_tags($str){ $pattern = ‘/<(“[^”]*”|'[^’]*’|[^>”‘])*>/’; return preg_replace($pattern,”,$str);

}

//Instance $HTML = ‘

ddddd

‘; echo strip_html_tags($html); echo ”
“;

$html = ‘

bb
aaa

‘; echo strip_html_tags($html);

?>

###

  1. Please write a function to verify whether the e-mail format is correct (regular is required)

preg_match(‘/^[w-.][email protected][w-]+(.w+)+$/‘,$email);

Related topic: please write a function with regular expression to verify whether the e-mail format is correct. (Xinzhong renyun)

###

  1. Please describe the main functions of POSIX style and Perl style compatible regular expressions by analogy

There are three main differences:

preg_ The regular in replace () can be written into shape, such as: “/ XXX / “and the regular in ereg_replace() needs to be written, such as” XXX “

preg_ Replace () can manipulate arrays, while ereg_ Replace() is not allowed

Use preg in reverse reference_ Replace() can use 0-99, while ereg_ The maximum number of replace() is 9

Preg using Perl compatible regular expression syntax_ The match () function is usually a faster alternative than ereg ().

###

  1. Please write and explain how to run the PHP script under the command line (write two ways) and pass parameters to the PHP script at the same time?

First enter the PHP installation directory

php -f d:/wamp/www/1. PHP, where the – f parameter specifies the PHP file to execute
php -r phpinfo (); Where – R means to execute PHP code directly without writing start and end tags

###

  1. Use regular expression to extract the specified attribute value of the specified tag in a piece of identification language (HTML or XML) code (the attribute value should be considered to be irregular, such as case insensitive, space between attribute name value and equal sign, etc.). Assuming that you need to extract the attr attribute value of the test tag, please build your own string containing the tag

Write the following functions:

<?php header(“content-type:text/html;charset=utf-8”);

function getAttrValue($str,$tagName,$attrName){ $pattern1=”/<“.$tagName.”(s+w+s*=s*([‘”]?)([^'”]*)())*s+”.$attrName.”s*=s*([‘”]?)([^'”]*)()(s+w+s*=s*([‘”]?)([^'”]*)(9))*s*>/i”;

$arr=array(); $re=preg_match($pattern1,$str,$arr);

if($re){ echo”

}

//Examples

$str1=””; getAttrValue ($str1,”test”,”attr”);// Find the value of attr attribute in the test tag, and the result is DDD

$str2=””;

getAttrValue ($str2,”test2″,”t1″);// Find the value of T1 attribute in test2 tag, and the result is T1 value

?>

###

26.What does the following code do?Explain what’s going on there.date);

This is to convert a date from mm / DD / yyyy format to DD / mm / yyyy format. Output 26 / 08 / 2003

###

27.What function would you use to redirect the browser to a new page?

A. Redir() b.header() c.location() d.redirect() answer: B redir() this is not a PHP function and will cause execution errors. Header () is the correct answer. The header () function sends header information, which can be used to turn the browser to another page, for example: header (“location:www.search-this.com/“)。Location() this is not a PHP function and will cause execution errors. Redirect() this is not a PHP function and will cause execution errors.

###

28.When turned on____________will_________your script with different variables from HTML forms and cookies.

A.show_ errors,enable B.show_ errors,show C.register_ globals,enhance D.register_ Globals, inject answer: C

###

  1. The parameter of a function cannot be a reference to a variable, except in PHP Ini____ Set to on.

allow_ call_ time_ pass_ Reference whether to enable forcing parameters to be passed by reference when a function is called

###

  1. In HTML language, the meta tag in the page header can be used to output the encoding format of the file. The following is a standard meta statement < meta http equiv = ‘content type’ content = ‘text / HTML; Charset = GBK ‘>, please write a function in PHP language to change the value of charset in the meta like tag in a standard HTML page to Big5.

Please note: (1) the complete HTML page needs to be processed, that is, not only this meta statement (2) ignore case (3) ‘and “are interchangeable here (4) the quotation marks around’ content type ‘are negligible, but’ text / HTML”; Charset = GBK ‘(5) pay attention to dealing with redundant spaces and write regular expressions as follows:

$reg1=”/(<metashttp-equivs=s([‘“]?)Content-Type()scontents=s([‘“])text/html;charset=)(UTF-8)()(s*/?>)/i”;

###

31. How to judge whether a string is a legal date pattern in PHP: 2007-03-13 13:13:13. No more than 5 lines of code are required.

<?php function checkDateTime($data){ if (date(‘Y-m-d H:i:s’,strtotime($data)) == $data) { return true; } else { return false; }

}

//Example $data = ‘2015-06-20 13:35:42’; var_ dump (checkDateTime ($data));// bool (true)

$data = ‘2015-06-36 13:35:42’; var_dump(checkDateTime($data));//bool(false)

?>

###

32. How to get the key value of an array in PHP?

Use key() to get the key name of the current element in the array, and use current() to return the value of the current element. Using array_ Keys () can get all the key names in the array. Using the foreach structure, foreach ($arr as value) can obtain the key name and value respectively through value.

###

  1. If the template is a smart template. How to use the section statement to display a group named $data.

For example:

$data=array(
0=>array(‘id’=>8,’name’=>’name1’),
1=>array(‘id’=>10,’name’=>’name2’),
2=>array(‘id’=>15,’name’=>’name3’)
);

Write the code on the template page? How do I display it if I use a foreach statement?

Use the section statement:

<{section name=test loop=$data start=0 step=1}>

id:<{$data[test].id}>

name:<{$data[test].name}>

<{sectionelse}>
Array is empty
<{/section}>

Use the foreach statement:

<{foreach from=$data item=test}>

id:<{$test.id}>

name:<{$test.name}>

<{foreachelse}>

Array is empty

<{/foreach}>

###

  1. Which option matches the regular expression below? (/.*xyzd/)

A.*****xyz

B.xyz1 C.xyz2 D.XYZ answer: C

###

  1. Which of the following errors cannot be obtained by the standard error controller?

A.E_ WARNING B.E_ USER_ ERROR C.E_ PARSE D.E_ Note answer: B

###

  1. Which of the following error types cannot be caught by a custom error handler?

A.E_ WARNING B.E_ USER_ ERROR C.E_ PARSE D.E_ Note answer: C

###

37. (^ s) | (S $) this regular expression is used to: _;

Matches a string that starts with 0 or more whitespace characters or ends with 0 or more whitespace characters

###

  1. Write a function to get the last day of last month

<?php

date_default_timezone_set(‘PRC’);

/*** get the last day of the previous month of the given month * @ param $date string the given date * @ return string the last day of the previous month*/

function get_last_month_last_day($date = ”){ if ($date != ”) { $time = strtotime($date);

} else { $time = time();

}

$day = date (‘j’,$time);// Get the day of the current month. Return date (‘y-m-d ‘, strtotime (“- {$day} days”, $time));}

//Test echo get_ last_ month_ last_ day (); echo “

###

  1. In many cases, we can set the access control of the test directory through the main configuration file of Apache, such asIP/testIf you need to set the access control permission of a subdirectory under test, can you modify it in the main configuration file? If not, how to solve it.

Yes, it can also be created under the subdirectory that needs to be controlled Htaccess file, write access control.

###

  1. If my website uses UTF-8 coding, what should I pay attention to in order to prevent random code?

Consider from the following aspects:

The database and tables are encoded with utf8

PHP connects to MySQL and specifies the database code as utf8 mysql_ query (“set names utf8”);

PHP file specifies that the header code is UTF-8 header (“content type: text / HTML; charset = UTF-8”);

The code of all documents under the website is utf8

The HTML file is encoded as UTF-8

###

  1. When you use get to transfer values in a URL, which function should be used to encode Chinese if there is garbled code in Chinese?

urlencode()

###

  1. Write two functions that encrypt variables?

md5(str);

###

  1. How to change 2009-9-2 10:30:25 into UNIX timestamp?

<?php

date_default_timezone_set(“PRC”);

//Convert string to UNIX timestamp $UNIX_ time = strtotime (“2009-9-2 10:30:45”); echo $unix_ time; echo “

//Format UNIX timestamp to normal time format echo date (“y-m-d H: I: s”, $unix_time);? >

###

  1. How to replace a string in GB2312 format with UTF-8 format?

<? PHP iconv (‘gb2312 ‘,’ UTF-8 ‘,’ quietly is a farewell flute ‘);? >

###

  1. If you need to output the user’s input as is, which function should you use before data warehousing?

Htmlspecialchars or htmlentities

###

  1. Write down the names of more than five PHP extensions you have used (tip: commonly used PHP extensions)

mb_ Sring, iconv, curl, Gd, XML, socket, mysql, PDO, etc

###

  1. Do you know MVC mode? Please write the names of more than three popular MVC frameworks in PHP (case insensitive)

Fleethp, Zend framework, CakePHP, symfony, ThinkPHP, Yii, CodeIgniter, etc

###

48. What is the principle of Web uploading files in PHP and how to limit the size of uploaded files?

The form for uploading files uses post mode, and enctype = ‘multipart / form data’ should be added to the form.

Generally, you can add a hidden field:, which is located in front of the file field.

The value of value is the client byte limit for uploading files. It can avoid the trouble that users find that the file is too large and the upload fails after spending time waiting to upload a large file.

Use the file field to select the file to upload. After clicking the submit button, the file will be uploaded to the temporary directory in the server and will be destroyed at the end of the script. Therefore, it should be moved to a directory on the server before the end of the script. You can use the function move_ uploaded_ File() to move the temporary file. To get the information of the temporary file, use$_ FILES。

The factors limiting the size of uploaded files are:

Client’s hidden domain Max_ FILE_ The value of size (can be bypassed).

Server side upload_ max_ filesize,post_ max_ Size and memory_ limit。 These items cannot be set by foot.

Custom file size limit logic. Even if the limitation of the server can be decided by itself, there will be situations that need to be considered individually. So this restriction is often necessary.

###

  1. Briefly describe the implementation principle of UBB code.

UBB code is a variant of HTML. We customize our tags through programs, such as “[a] use of UBB in PHP [/ a]”. Its essence is to find the [a] [/ a] tag and replace it with standard HTML. In short, it is to simplify the standard HTML tag through technical means, and the output result is still standard HTML.

If you understand the principle of UBB, it’s not difficult to make a simple UBB editor. Compared with editors such as fck, the biggest advantage of UBB code is that the code is simple and has few functions. A simple UBB only needs one file, and the UBB tag can be defined by yourself, which is very convenient to change. In PHP, you can label HTML by using the replacement function and convert the tag when outputting.

###

  1. How to save files to the specified directory? How to avoid the problem of uploading files with duplicate names?

You can set the save directory of the uploaded file by yourself and piece it together with the file name to form a file path. Use move_ uploaded_ File(), you can save the file to the specified directory. You can get the file suffix from the uploaded file name, and then rename the file by using timestamp + random number + file suffix, so as to avoid duplicate names.

###

51._____ Function can return the name of the function called in any line of the script. This function is also often used in debugging to determine how errors occur.

debug_print_backtrace()

###

  1. How can I traverse array IDS in Smarty template syntax

{section name=temp loop=$ids}
{if $ids[temp].id==500}
{$ids[temp].id}
{esle}
{$ids[temp].id}
{/if}
{/section}

###

  1. How to obtain the current time in Smarty template syntax and output it in the format of y-m-d HS? (Yiyou)

Use {$smart. Now} to get the current time. The UNIX system timestamp is obtained. Use the variable adjuster to format it, as follows:

{$smarty.now|date_format:“%Y-%m-%d%H:%M:%S”}

###

  1. How to get the global environment variables of PHP in Smarty template syntax

$smarty. get. Variable # displays the value of the specified variable passed through get
$smarty. post. Variable # displays the value of the specified variable passed through post
$smarty. cookies. Variable # displays the value of the variable specified in the cookie
$smarty. server. SERVER_ Name # displays the value of the server variable$_ Server series variables
$smarty. env. Path # displays the value of the system environment variable$_ Env series variables
$smarty. session. Variable # displays the value of the specified variable in the session
$smarty. request. Variable # displays the value of the variable specified in post, get and cookie

###

  1. How to use custom functions in Smarty templates

The template separator is used to contain parameters, and the HTML attribute is used to pass parameters, for example: {html_image file = “pumpkin. JPG”}

###

  1. List the PHP system function libraries you know, such as math function libraries

Mysql, Gd, PDO, XML, zip, filesystem, mail, etc

###

  1. If you are asked to write a function to realize UTF-8 to GB2312, how should the name of the function be named? (Yiyou)

utf8_ to_ GB2312 or utf8togb2312

###

  1. Please describe the purpose of the following URL Rewrite Rule.

<IfModulemod_rewrite.c>
RewriteEngineon
RewriteCond%{REQUEST_FILENAME}!-f
RewriteCond%{REQUEST_FILENAME}!-d
RewriteBase/
RewriteRule./index.php[L]

If request_ If the filename file exists, you can directly access the file without the following rewrite rules. If request_ If the filename directory exists, you can directly access the directory without the following rewrite rule/ index. PHP [l] means to give all requests to index PHP processing.

###

59.Warning:Cannot modify header information-headers already sent by (output started at D:srcinit.php:7) in D:srcinit. PHP on line10 under what circumstances will PHP report this warning message?

Usually in header and set_ Cookies and sessions_ If there is output (including spaces) in front of the start function, this warning message will be reported
Remember to leave comments if you have questions; I don’t mind recommending these messy things I wrote to friends who think it’s useful!

This work adoptsCC agreement, reprint must indicate the author and the link to this article

There are great scholars in conversation and laughter, and there are no white men in communication!