2021-PHP core technology classic interview questions

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

<?php
    /**
     * Create multi-level directory
     * @param $path string Directory to create
     * @param $mode int The mode of creating directory can be ignored under windows
     */

    function create_dir($path,$mode = 0777)
    {
        if (is_dir($path)) {
            # If the directory already exists, it will not be created
            echo "The directory already exists";
        } else {

            # Does not exist, create
            if (mkdir($path,$mode,true)) {
                echo "Directory created successfully";
            } else {

                echo "Failed to create directory";
            }
        }
    }

?>

2. Write out the characteristics of smarty template

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

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

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

6. Please write a PHP code to ensure that multiple processes write 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);

?>

7. Write a function to extract 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

<?php

    // Scheme I
    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 II
    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 "<br />";
    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)

8. 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;
            }
        }
    }

?>

9. Briefly describe the implementation principle of unlimited classification in the forum.

Create a category table as follows:

CREATE TABLE category(

cat_id smallint unsigned not null auto_increment primary key comment'category ID',
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 category, it will be saved in $list, and take 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;
    }

?>

10. 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();
        }

        // Under 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 "<br />";
    echo releative_path($a,$c);//The result is a/b/c/d
    echo "<br />";
    echo releative_path($a,$d);//The result is/
    echo "<br />";

?>

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

12. There is a web page address, such as the homepage of PHP development resources network: http://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");

13. Talk about 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 the interactive interface and outputs the data,
The controller layer is responsible for receiving requests and distributing them to the corresponding model for processing, and then calls the view layer to display them.

14.What does the GD library do?

GD library provides a series of API s 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 has been modified, it can be detected and recompiled (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:website");//Direct jump
header("refresh:3;url=http://axgle.za.NET "); / / jump in three seconds

Method 2: using meta

echo"<meta http-equiv=refresh content='0;url=website'>";

18. Can PHP connect to databases such as sql server/oracle?

sure

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

20. 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:<script type='text/javascript'>alert('cc');</script>";

    $pattern = '/<script[^>]*?>.*?</script>/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);

    }

    // example
    $html = '<p id="">ddddd<br /></p>';
    echo strip_html_tags($html);
    echo "<br />";

    $html = '<p id=">">bb<br />aaa<br /></p>';
    echo strip_html_tags($html);

?>

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

preg_match('/^[w-.]+@[w-]+(.w+)+$/',$email);

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

23. Please explain 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().

24. 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 among-f Parameter specifies the to execute php file
php -r phpinfo(); among-r Indicates direct execution php Code, no need to write start and end tags

25. 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"<br/>$arr[6]={$arr[6]}";
        }else{
            echo"<br/>Can't find.";
        }

    }

    // Examples

    $str1="<test attr='ddd'>";
    getAttrValue($str1,"test","attr");//Find the value of attr attribute in the test tag, and the result is ddd

    $str2="<test2 attr='ddd'attr2='ddd2't1="t1 value"t2='t2 value'>";

    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

29. The parameter of a function cannot be a reference to a variable, unless 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

30. In HTML language, the meta tag at the head of the page 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 that:
(1) You need to process the complete html page, that is, not only this meta statement
(2) Ignore case
(3) 'and' are interchangeable here
(4) The quotation marks around 'content type' can be ignored, but 'text/html;charset=gbk 'not on both sides
(5) Pay attention to dealing with extra spaces
Write a regular expression as follows:

$reg1="/(<metas*http-equivs*=s*(['"]?)Content-Type()s*contents*=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;
        }

    }

    // Examples
    $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.

33. 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}><br/>
name:<{$data[test].name}><br/><br/>

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

Use the foreach statement:

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

id:<{$test.id}><br/>

name:<{$test.name}><br/><br/>

<{foreachelse}>

Array is empty

<{/foreach}>

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

A.*****xyz

B.xyz1
C.*xyz2
D.*xyz
Answer: C

35. 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_NOTICE
Answer: B

36. Which of the following error types cannot be captured by a custom error handler?

A.E_WARNING
B.E_USER_ERROR
C.E_PARSE
D.E_NOTICE
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

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

<?php

    date_default_timezone_set('PRC');

    /**
     * Gets the last day of the previous month of a given month
     * @param $date string Given date
     * @return string Last day of last month
     */

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

        } else {
            $time = time();

        }

        $day = date('j',$time);//Gets the day of the current month that the date is
        return date('Y-m-d',strtotime("-{$day} days",$time));
    }

    // test
    echo get_last_month_last_day();
    echo "<br />";
    echo get_last_month_last_day("2013-3-21");
?>

39. In many cases, we can set the access control of the test directory through the main configuration file of apache, such as http://IP/test If 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.

40. If my website uses utf-8 code, 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

<meta http-equiv="Content-Type"content="text/html;charset=utf-8"/>

41. When using get to transfer values in the url, if there is garbled code in Chinese, which function should be used to encode Chinese?

urlencode()

42. Write two functions that encrypt variables?

md5(str);

43. 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 "<br />";

    // Format Unix timestamp to normal time format
    echo date("Y-m-d H:i:s",$unix_time);
?>

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

<?php
    iconv('GB2312','UTF-8','Quietly is a farewell Sheng Xiao');
?>

45. If it is necessary to output the user's input as is, which function should be used before data warehousing?

htmlspecialchars or htmlentities

46. Write out 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

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

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

49. 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. It's easy to change. In php, html can be tagged by using the replacement function, Label conversion during output.

50. 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() to 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._____ The function can return the name of the function that is called in any row in the script. This function is also often used in debugging to determine how errors occur.

debug_print_backtrace()

52. How can I traverse array ids in Smarty template syntax

{section name=temp loop=$ids}
    {if $ids[temp].id==500}
        <span style='color:#f00;'>{$ids[temp].id}</span>
    {esle}
        {$ids[temp].id}
    {/if}
{/section}

53. How to get the current time in Smarty template syntax and use Y-m-d Hs format output?

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"}

54. 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 #Display the SERVER variable value$_ SERVER series variables
$smarty.env.PATH #Display system environment variable values$_ 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

55. 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"}

56. List the php system function libraries you know, such as math function libraries

mysql, gd, pdo, XML, zip, filesystem, mail, etc

57. If you are asked to write a function to realize Utf-8 to gb2312, how should the name of the function be named?

utf8_to_gb2312 perhaps utf8togb2312

58. Please describe the intention of the following URL rewriting rules.

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

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

Keywords: PHP

Added by c0le on Wed, 09 Feb 2022 02:07:15 +0200