PHP Interview Questions and Sample Code Answers

This article presents a comprehensive collection of PHP interview questions covering topics such as directory creation, Smarty template features, safe mode restrictions, file handling, regular expressions, MVC concepts, and includes complete code examples for each solution.

php Courses
php Courses
php Courses
PHP Interview Questions and Sample Code Answers

1. Write a PHP function that creates multi‑level directories.

<?php
/**
 * 创建多级目录
 * @param $path string 要创建的目录
 * @param $mode int 创建目录的模式,在windows下可忽略
 */
function create_dir($path,$mode = 0777)
{
    if (is_dir($path)) {
        # 如果目录已经存在,则不创建
        echo "该目录已经存在";
    } else {
        # 不存在,创建
        if (mkdir($path,$mode,true)) {
            echo "创建目录成功";
        } else {
            echo "创建目录失败";
        }
    }
}
?>

2. List the characteristics of the Smarty template engine.

Fast, compiled, uses caching, supports plugins, and provides powerful presentation logic.

3. When PHP safe_mode is enabled, which functions are affected? At least six are listed.

Functions such as chdir, move_uploaded_file, chgrp, parse_ini_file, chown, rmdir, copy, rename, fopen, require, mkdir, unlink are restricted or disabled. Safe mode was deprecated in PHP 5.3 and removed in PHP 5.4.

4. Which function(s) would you use to fetch a remote image to the local server? file_get_contents or curl 5. Explain PHP's garbage collection mechanism.

PHP uses reference counting; each object has a counter that increments on new references and decrements when references are destroyed. When the counter reaches zero, the memory is released.

6. Provide a PHP code snippet that ensures multiple processes can write to the same file safely.

<?php
$fp = fopen("lock.txt","w+");
if (flock($fp,LOCK_EX)) {
    //获得写锁,写数据
    fwrite($fp, "write something");
    // 解除锁定
    flock($fp, LOCK_UN);
} else {
    echo "file is locking...";
}
fclose($fp);
?>

7. Write a function to efficiently extract a file extension from a standard URL.

<?php
function getExt1($url){
    $arr = parse_url($url);
    $file = basename($arr['path']);
    $ext = explode('.', $file);
    return $ext[count($ext)-1];
}
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);
?>

8. Write a recursive function to traverse all files and sub‑folders within a directory.

<?php
function my_scandir($dir){
    $files = array();
    if(is_dir($dir)){
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($dir."/".$file)) {
                        $files[$file] = my_scandir($dir."/".$file);
                    } else {
                        $files[] = $dir."/".$file;
                    }
                }
            }
            closedir($handle);
            return $files;
        }
    }
}
?>

9. Describe the principle behind implementing infinite category trees in a forum.

Using a table with fields cat_id, cat_name, and parent_id, a recursive function can build a flat list representing the hierarchy.

<?php
function tree($arr,$pid=0,$level=0){
    static $list = array();
    foreach ($arr as $v) {
        if ($v['parent_id'] == $pid) {
            $v['level'] = $level;
            $list[] = $v;
            tree($arr,$v['cat_id'],$level+1);
        }
    }
    return $list;
}
?>

10. Write a function to compute the relative path between two file paths.

<?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;
        }
    }
    if ($i==1) {
        $return_path = array();
    }
    if ($i != 1 && $i < $len) {
        $return_path = array_fill(0, $len - $i,"..");
    }
    if ($i == $len) {
        $return_path = array('./');
    }
    $return_path = array_merge($return_path,array_slice($arr1,$i));
    return implode('/',$return_path);
}
?>

11. Difference between mysql_fetch_row() and mysql_fetch_array(). mysql_fetch_row() returns a numeric indexed array, while mysql_fetch_array() returns both numeric and associative keys.

12. How to retrieve the contents of a web page in PHP.

<?php
$readcontents = fopen("http://www.phpres.com/index.html","rb");
$contents = stream_get_contents($readcontents);
fclose($readcontents);
echo $contents;
?>

13. Briefly explain MVC.

Model handles data and database interactions, View renders the user interface, and Controller processes requests, invokes the Model, and selects the View.

14. What does the GD library do?

Provides APIs for image creation and manipulation such as generating thumbnails, adding watermarks, and drawing graphics; built into PHP since version 4.3.0.

15. Which function opens a file for reading and writing?

Answer: fopen().

16. Explain the principle of Smarty.

Smarty separates business logic from presentation by compiling templates into PHP files, caching compiled output, and optionally caching final HTML, improving performance.

17. How to perform page redirection in PHP.

header("Location: url"); // direct redirect
header("refresh:3;url=http://example.com"); // delayed redirect

18. Can PHP connect to SQL Server/Oracle databases?

Yes, using appropriate extensions such as sqlsrv, oci8, PDO, etc.

19. Tools for version control.

SVN, CVS, Git.

20. Regular expression to strip all <script> tags and their content.

<?php
$script = "以下内容不显示:<script type='text/javascript'>alert('cc');</script>";
$pattern = '/<script[^>]*?>.*?</script>/si';
echo preg_replace($pattern, "脚本内容", $script);
?>

21. Regular expression to remove all HTML tags from a string.

Use strip_tags() or a custom preg_replace() pattern.

22. Function to validate email format using a regular expression. preg_match('/^[\w.-]+@[\w-]+(\.\w+)+$/', $email); 23. Compare POSIX‑style and PCRE‑style regex functions.

PCRE functions ( preg_*) use patterns like /pattern/, support arrays, and allow up to 99 back‑references; POSIX functions ( ereg_*) use plain patterns, cannot handle arrays, and limit back‑references to 9.

24. Two ways to run a PHP script from the command line and pass arguments.

php -f d:/wamp/www/1.php
php -r "phpinfo();"

25. Regular expression to extract the attr attribute from a <test> tag.

<?php
function getAttrValue($str,$tagName,$attrName){
    $pattern = "/<".$tagName."(\s+\w+\s*=\s*(['\"]?)([^'\"]*)())*\s+".$attrName."\s*=\s*(['\"]?)([^'\"]*)()/i";
    if(preg_match($pattern,$str,$arr)){
        echo "<br/>$arr[6]={$arr[6]}";
    } else {
        echo "<br/>没找到。";
    }
}
$str1 = "<test attr='ddd'>";
getAttrValue($str1,"test","attr");
?>

26. Code that converts a date from MM/DD/YYYY to DD/MM/YYYY.

Explanation: Uses explode() and re‑ordering of array elements to output the new format.

27. Function to redirect the browser to a new page.

Answer: header().

28. Which PHP directive registers global variables from forms and cookies?

Answer: register_globals (now deprecated).

29. Which php.ini setting allows passing arguments by reference? allow_call_time_pass_reference must be enabled.

30. Function to change the charset in a <meta> tag from gbk to big5.

<?php
$reg1 = "/(<meta\s+http-equiv\s*=\s*(['\"]?)Content-Type\s*content\s*=\s*(['\"]?)text\/html;charset=)(UTF-8)(.*?)/i";
?>

31. Validate a datetime string YYYY-MM-DD HH:MM:SS in five lines.

<?php
function checkDateTime($data){
    return date('Y-m-d H:i:s',strtotime($data)) == $data;
}
?>

32. How to obtain array keys in PHP.

Use key(), array_keys(), or iterate with foreach.

33. Display a Smarty variable $data using {section} and {foreach}.

Examples of both syntaxes are provided.

34. Which option matches the regex /.*xyzd/?

Answer: C.

35. Which error type cannot be captured by a custom error handler?

Answer: E_USER_ERROR.

36. Which error type cannot be captured by a custom error handler?

Answer: E_PARSE.

37. Meaning of regex (^\s)|(\s$).

Matches strings that start or end with whitespace.

38. Function to get the last day of the previous month.

<?php
function get_last_month_last_day($date=''){
    $time = $date!='' ? strtotime($date) : time();
    $day = date('j',$time);
    return date('Y-m-d',strtotime("-{$day} days",$time));
}
?>

39. Controlling access to a sub‑directory via Apache configuration.

Use an .htaccess file in the sub‑directory.

40. Measures to avoid UTF‑8 garbled output.

Database tables set to UTF‑8.

Set MySQL client charset with SET NAMES utf8.

Send HTTP header Content-Type: text/html; charset=utf-8.

Ensure all source files are saved as UTF‑8.

Specify charset in HTML <meta> tag.

41. Function to encode Chinese characters in URL parameters. urlencode() 42. Two functions for encrypting variables. md5() and sha1() (or other hash functions).

43. Convert 2009-9-2 10:30:25 to a Unix timestamp.

<?php
$unix_time = strtotime("2009-9-2 10:30:45");
?>

44. Convert a GB2312 string to UTF‑8.

<?php
iconv('GB2312','UTF-8','悄悄是别离的笙箫');
?>

45. Function to safely output user‑submitted content before storing.

Use htmlspecialchars() or htmlentities().

46. List of commonly used PHP extensions.

mbstring, iconv, curl, GD, XML, sockets, MySQL, PDO, etc.

47. Popular PHP MVC frameworks.

Laravel, Symfony, CodeIgniter, Yii, Zend Framework, CakePHP.

48. How file uploads work in PHP and how to limit size.

Use enctype="multipart/form-data", hidden MAX_FILE_SIZE, and server settings upload_max_filesize, post_max_size.

49. Principle of UBB code.

UBB tags are custom markup that are replaced by standard HTML via string replacement functions.

50. Save uploaded files to a specific directory and avoid name collisions.

Use move_uploaded_file() and rename files with a timestamp plus random number.

51. Function that returns the name of the calling function for debugging. debug_print_backtrace() 52. Iterate over an array $ids in Smarty. {section name=temp loop=$ids}...{/section} 53. Output current time in Smarty with format Y-m-d H:s. {$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} 54. Access PHP global variables in Smarty.

Use $smarty.get, $smarty.post, $smarty.server, etc.

55. Use custom functions in Smarty templates.

Define the function in PHP and call it with Smarty syntax, e.g., {html_image file="pumpkin.jpg"}.

56. List of PHP system function libraries.

MySQL, GD, PDO, XML, Zip, Filesystem, Mail, etc.

57. Naming a function that converts UTF‑8 to GB2312.

Suggested names: utf8_to_gb2312 or utf8togb2312.

58. Explain the purpose of the given URL rewrite rules.

If the requested file or directory does not exist, rewrite the request to index.php for front‑controller handling.

59. When does PHP emit the warning "Cannot modify header information – headers already sent"?

When any output (including whitespace) is sent before calling header(), setcookie(), or session_start().

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendPHPcodeweb-development
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.