Top PHP Interview Questions and Answers for Developers
This article compiles a comprehensive set of PHP interview questions covering fundamentals, session and cookie handling, database transactions, MySQL optimization, version control tools, string manipulation, HTTP status codes, MVC concepts, and practical coding tasks with detailed answers and code examples.
Basic Questions
1. What is the difference between GET and POST submission methods? GET sends data via URL parameters, while POST transmits data in the request body, allowing larger payloads.
2. What is the difference between session and cookie? Session data is stored on the server (e.g., in a directory defined by session_dir) and is unique per user, whereas a cookie is stored on the client side (typically in the browser's temporary files) and can be set with an expiration time.
3. What is a transaction in a database? A transaction is a unit of work consisting of multiple SQL statements that either all succeed (commit) or all fail (rollback), ensuring data integrity.
Short Answer Questions
1. Print yesterday's date in the format 2006-5-10 22:21:21. echo date('Y-m-d H:i:s', strtotime('-1 days')); 2. Difference between echo(), print(), and print_r(). echo outputs one or more strings; print outputs a simple variable and returns 1; print_r prints human‑readable information about arrays or objects.
3. Template engines that separate HTML from PHP. Smarty, Template, Lite, phemplate.
4. Version control tools. SVN, Git.
5. How to reverse a string? echo strrev($a); 6. MySQL optimization methods (multiple points).
Select appropriate field types, set NOT NULL, use ENUM where possible.
Replace sub‑queries with JOINs, e.g., delete customers without orders using DELETE with NOT IN, or retrieve them with SELECT and NOT IN, then improve speed with LEFT JOIN.
Replace manual temporary tables with UNION.
Use transactions to guarantee atomic operations, e.g., BEGIN, INSERT, SELECT, COMMIT.
Lock tables with LOCK TABLE ... READ, ... WRITE before updates, then UNLOCK.
Use foreign keys to enforce referential integrity (ON DELETE CASCADE) and ensure InnoDB engine.
Create indexes (normal, unique, primary) to speed up queries.
Optimize queries by avoiding functions on indexed columns and using range conditions.
7. What does PHP stand for? PHP is a server‑side scripting language for creating dynamic web pages.
8. MySQL functions for current time and date formatting. now() returns the current timestamp; date() formats dates.
9. How to truncate a Chinese string without garbling?
function GBsubstr($string, $start, $length) {
if (strlen($string) > $length) {
$str = null;
$len = $start + $length;
for ($i = $start; $i < $len; $i++) {
if (ord(substr($string, $i, 1)) > 0xa0) {
$str .= substr($string, $i, 2);
$i++;
} else {
$str .= substr($string, $i, 1);
}
}
return $str . '...';
} else {
return $string;
}
}10. Have you used version control software? Name it. git.
11. Have you used a template engine? Name it. Smarty.
12. Briefly describe your most proud development project. Information classification (free‑form answer).
13. How would you handle high traffic on a website? Verify server hardware, use DB read/write splitting, optimize tables, limit hotlinking, control large file downloads, and distribute traffic across multiple hosts.
14. PHP code to display client IP and server IP.
echo $_SERVER['REMOTE_ADDR']; // client IP
// or getenv('REMOTE_ADDR');
echo $_SERVER['SERVER_ADDR']; // server IP15. Difference between include and require; which statement can replace them to avoid multiple inclusions? require is unconditional and fatal on failure; include returns a warning on failure. Use require_once or include_once to prevent duplicate inclusion.
16. How to modify session lifetime?
// Method 1: set session.gc_maxlifetime in php.ini and restart Apache
// Method 2:
$savePath = "./session_save_dir/";
$lifeTime = $hours * 3600;
session_save_path($savePath);
session_set_cookie_params($lifeTime);
session_start();
// Method 3: setcookie() and session_set_cookie_params($lifeTime);17. How to fetch the content of a webpage (e.g., http://www.phpres.com/index.html)?
// Method 1 (PHP5+):
$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");18. HTTP 1.0 status code 401 meaning and header to indicate file not found. 401 means unauthorized; use header("Location:www.xxx.php") for redirection.
19. What is required for a heredoc string in PHP? It must start with <<<IDENTIFIER and end with the same identifier on a line by itself.
$str = <<<SHOW
my name is Jiang Qihui!
SHOW;20. Compare ASP, PHP, and JSP. ASP uses VBScript, PHP is a free, cross‑platform embedded scripting language with extensive database support, and JSP compiles to servlets running on the Java VM, offering stronger performance after the first request.
21. What is MVC? Model‑View‑Controller separates an application into three components: the model (data), the view (presentation), and the controller (logic).
22. SQL to list top 10 users by post count.
SELECT * FROM `members` ORDER BY posts DESC LIMIT 0,10;23. Purpose of error_reporting. Sets the level of error reporting and controls which errors are displayed.
24. Function to validate an email address.
function checkEmail($email) {
$pregEmail = "/([a-z0-9]*[-_/.]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a-z0-9]+)+[/.][a-z]{2,3}([/.][a-z]{2})?/i";
return preg_match($pregEmail, $email);
}25. Get the current script name.
$script_name = basename(__FILE__);
print_r($script_name);26. JavaScript dialog functions and focus function. alert(), prompt(), confirm() for dialogs; focus() to set input focus.
27. JavaScript redirect function and how to include an external JS file.
window.location.href = "newpage.php";
<script type="text/javascript" src="js/js_function.js"></script>28. Difference between foo() and @foo(). @ suppresses error output from the function call.
29. Declare a class named "myclass" without methods or properties. class myclass { } 30. Instantiate an object of "myclass". new myclass(); 31. Access and set a class property.
$object = new myclass();
$value = $object->test;
$object->test = "info";32. Difference between mysql_fetch_row() and mysql_fetch_array(). fetch_row returns a numeric array; fetch_array can return both numeric and associative arrays.
33. What is the GD library used for? GD provides APIs for image processing, such as generating thumbnails or adding watermarks.
34. Ways to output HTML from PHP. echo "<a href='index.php'>aaa</a>"; 35. Which function can open a file for read/write? fopen().
36. Which option does NOT add "john" to the $users array? $users ||= 'john'; (does not push the value).
37. What does the following code output?
$num = 10;
function multiply() {
$num = $num * 10; // $num is undefined inside the function, so it remains 10
}
multiply();
echo $num; // outputs 1038. PHP code to query all rows where name = "张三" and print them.
$mysql_db = mysql_connect("local","root","pass");
@mysql_select_db("DB", $mysql_db);
$result = mysql_query("SELECT * FROM `user` WHERE name='张三'");
while ($rs = mysql_fetch_array($result)) {
echo $rs["tel"] . $rs["content"] . $rs["date"];
}39. Use the following class and explain its purpose.
class test {
function Get_test($num) {
$num = md5(md5($num)."En");
return $num;
}
}
$testnum = "123";
$object = new test();
$encrypt = $object->Get_test($testnum);
echo $encrypt; // returns a double‑MD5 hash of the input40. SQL statements for INSERT, UPDATE, DELETE on a user table.
// INSERT
mysql_query("INSERT INTO `user` (name,tel,content,date) VALUES ('小王','13254748547','高中毕业','2007-05-06')");
// UPDATE (set date to current system date for 张三)
$nowDate = date("Ymd");
mysql_query("UPDATE `user` SET date='$nowDate' WHERE name='张三'");
// DELETE (remove all records for 张四)
mysql_query("DELETE FROM `user` WHERE name='张四'");41. Meaning of data types int, char, varchar, datetime, text and difference between char and varchar. int – integer; char – fixed‑length string; varchar – variable‑length string; datetime – date and time; text – large text block. char reserves the defined length, varchar stores only the actual length.
42. Output of the ternary expression. The code prints 4.
43. Functions to check if a variable is set and if it is empty. isset($var) and empty($var).
44. Function to get the number of rows in a result set. mysql_num_rows($result).
45. Print the first element of an array. echo $array[0];.
46. Print the first character of a string. echo $a{0}; or echo substr($a,0,1);.
47. Can PHP connect to SQL Server or Oracle? Yes, PHP can connect to those databases.
48. PHP5 access modifiers. public, private, protected.
49. PHP5 constructor and destructor. __construct and __destruct.
Programming Tasks
1. Function to extract a file extension from a URL.
function getExt($url) {
$arr = parse_url($url);
$file = basename($arr['path']);
$ext = explode('.', $file);
return $ext[1];
}Alternative implementation handling query strings:
function getExt($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);
}
}2. Function to calculate the relative path from one file to another.
function getRelativePath($a, $b) {
$returnPath = array(dirname($b));
$arrA = explode('/', $a);
$arrB = explode('/', $returnPath[0]);
for ($n = 1, $len = count($arrB); $n < $len; $n++) {
if ($arrA[$n] != $arrB[$n]) {
break;
}
}
if ($len - $n > 0) {
$returnPath = array_merge($returnPath, array_fill(1, $len - $n, '..'));
}
$returnPath = array_merge($returnPath, array_slice($arrA, $n));
return implode('/', $returnPath);
}
// Example usage:
$a = '/a/b/c/d/e.php';
$b = '/a/b/12/34/c.php';
echo getRelativePath($a, $b); // outputs ../../c/d3. Function to recursively scan a directory.
function my_scandir($dir) {
$files = array();
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false) {
if ($file != ".." && $file != ".") {
if (is_dir($dir . "/" . $file)) {
$files[$file] = scandir($dir . "/" . $file);
} else {
$files[] = $file;
}
}
}
closedir($handle);
return $files;
}
}4. Principle of implementing infinite category hierarchy in a forum. Store categories with parent IDs, recursively query children, and build a nested structure (e.g., using a recursive function that outputs <option> elements with indentation).
5. SQL to list article titles sorted by comment count (including zero comments).
SELECT message.id, message.title,
IF(message.`hits` IS NULL, 0, message.`hits`) AS hits,
IF(comment.id IS NULL, 0, COUNT(*)) AS number
FROM message
LEFT JOIN comment ON message.id = comment.id
GROUP BY message.id
ORDER BY number DESC;6. Generate a drop‑down list of categories from a category table.
function categoryList() {
$result = mysql_query("SELECT category_id, categroy_name FROM category")
or die("Invalid query: " . mysql_error());
echo "<select name='category'>
";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['category_id'] . "'>" . $row['categroy_name'] . "</option>
";
}
echo "</select>";
}7. Function to generate a nested category <select> using recursion (class example).
class cate {
function Get_Category($category_id = 0, $level = 0, $default_category = 0) {
global $DB;
$sql = "SELECT * FROM category ORDER BY categoryID DESC";
$result = $DB->query($sql);
while ($row = $DB->fetch_array($result)) {
$category_array[$row['categoryParentID']][$row['categoryID']] = array(
'id' => $row['categoryID'],
'parent' => $row['categoryParentID'],
'name' => $row['categoryName']
);
}
if (!isset($category_array[$category_id])) return "";
foreach ($category_array[$category_id] as $key => $cat) {
$selected = ($cat['id'] == $default_category) ? "selected" : "";
echo "<option $selected value='" . $cat['id'] . "'>" . str_repeat('—', $level) . $cat['name'] . "</option>
";
$this->Get_Category($key, $level + 1, $default_category);
}
unset($category_array[$category_id]);
}
function getFlush($category_id = 0, $level = 0, $default_category = 0) {
ob_start();
$this->Get_Category($category_id, $level, $default_category);
$out = ob_get_contents();
ob_end_clean();
return $out;
}
}These questions and code samples provide a solid foundation for preparing for PHP developer interviews.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
