Olibr Blogs

Blog > All Engineering Topics > Top PHP Interview Questions in 2024

Top PHP Interview Questions in 2024

by Pranisha Rai
top 20 php interview questions
Pointer image icon

Introduction

If you have a PHP interview coming up, then you must be well-prepared with these common interview questions. In this article, we have covered the most frequently asked PHP interview questions. So, get ready to master all 60 questions and ace your PHP interview.

best software companies

Don't miss out on your chance to work with the best!

Apply for top job opportunities today!

Pointer image icon

Basic PHP Interview Questions with Answers

Basic interview questions PHP

1. Explain the Session in PHP.
Sessions act as storage to store data on the server. It stays active until the user is active for a specified period, and once the user closes the browser, it will be inactive. In comparison with PHP cookies, sessions are secure and handle huge amounts of data. 

2. What is the major difference between the include() and require() functions?
Both functions are used in PHP to include external files in another PHP file. The difference lies in handling errors, where
include() generates a warning and require() generates fatal errors.
 

3. Define Public, Private, and Protected.

Public, private, and protected are the access specifiers in PHP.  

  • Public Access Specifier: When a programmer specifies any variable or function as public in the program, that can be called from the instances of an object, another class, or from anywhere in the program. 
  • Private Access Specifier: If any function or variable is specified as private, then those variables and functions can be accessed by that class only. 
  • Private Access Specifier: Variables and functions can be accessed from the inherited and extended classes. But it cannot be accessed outside the class. 

4. What is the use of cURL?
cURL is the PHP library through which any URL can connect easily. 

5. Why do we need to use “action” and “enctype” attributes in an HTML form? 

The action attribute determines whether to send the form data in the form submission or not. The enctype determines how the form data should be encoded when submitting it to the server.

6. What does header() mean in PHP? 
It is used to send a raw HTTP header by using HTML tags or blank lines in a file.

7. Is PHP a case-sensitive scripting language?
Variables declared in PHP are case-sensitive, but their functions are not.

8. Why do we use count() and array() functions in PHP?
array() functions are used to check whether the value exists in an array or not, and count() is used to count all elements in an array or object.

9. What are the popular frameworks for PHP? 

  • Laravel 
  • CodeIgniter 
  • Symphony 
  • Yii 2 
  • CakePHP 
  • Zend Framework 

10. Which function is used to register a variable in a PHP session? 

We need to use the session_register() function. But first, we must set a value in $_SESSION Global to pass the username to the function.

11. Can you explain the rules of naming variables in PHP?

  • First, while writing the code in PHP, one should always use the dollar symbol ($) before the variable. 
  • Secondly, variables in PHP do not contain It does not include characters such as %, -, &, and +. 
  • Thirdly, the variable must begin with a letter or underscore, and it should consist of numbers. 
  • Lastly, PHP variables are case-sensitive. 

12. How do you define a Constant? 
By using the define() function directive, like define (“MYCONSTANT”,150).

13. How many loops are there in PHP?

There are four types of loops in PHP; those are: 

  • for 
  • while 
  • do while 
  • And foreach

14. How do you add a file to a PHP Page?
By using the “include()” and “require()” functions within the file path as its parameters.

15. How do we retrieve the data in the result set of MySQL using PHP?

By using the following SQL queries:

  • mysql_fetch_row  
  • mysql_fetch_array 
  • mysql_fetch_object 
  • mysql_fetch_assoc

16. How do you strip whitespace from the beginning and end of a String? 
By using the trim() function, we can remove the whitespace.

17. What is the difference between a break and a continue statement? 

  • Break: It is used to terminate the iteration of any kind of loop and execute the next code that is outside that scope. 
  • Continue: It is used to skip the continuation of the ongoing iteration of the loop and continue with the next iteration.

18. What is the use of rand() in PHP?
It is used to generate random numbers. We can use rand(6, 12) to generate a random number between 6 and 12.

19. What is the difference between PHP and JavaScript?

PHPJavaScript
It is used to build the backend of websites and runs on a serverIt can be used to build both the backend and the frontend
Its codes are secureIt runs on a browser
PHP scripts can only be integrated with HTMLJavaScript code is not secure

20. How many errors are there in PHP? 

There are four types of errors in PHP: notice error, fatal error, syntax error, and warning error.  

  • Notice Error: It occurs whenever a developer tries to access an undefined variable. 
  • Fatal Error: Whenever developers try to call a function that does not exist, a fatal error stops the execution right away. 
  • Syntax Error: If there is a mistake in the syntax then PHP will throw a syntax error. 
  • Warning Error: It occurs whenever there is a missing file in PHP code or usage of incorrect parentheses.

21. Why do we need to use Escaping in PHP? 
It is used to avoid misinterpretations during execution and minimize the ambiguity of interpreters.

22. What is the key difference between Print and Echo in PHP?
Print and Echo are used to display the output data in PHP, but there is a slight difference between these functions. The print function can only take one output at a time and return a value. It is always used with parentheses, whereas echo is a language construct that does not require parentheses. Unlike print, it can take multiple strings at once.

23. How does PHP interact with HTML Code?

There are two ways in which PHP can interact with HTML code:

  • PHP code can be embedded with HTML code in the.html extension. 
  • PHP code and HTML tags can merge into .PHP files.

24. Write a code to display a URL from the Current Webpage
<?php 
echo $_SERVER[‘PHP_SELF‘]; 
?>

25. What are the disadvantages of PHP?

  • PHP performance will lag when additional tools and frameworks are used. 
  • It’s open source, and there’s a high security concern. 
  • PHP is flexible, but there are limitations to altering and customizing online applications. 
  • It has fewer debugging tools in comparison with other programming languages.

26. Does PHP support Multiple Inheritance? 
No, it does not. PHP supports single inheritance, which can be inherited from only one base class. However, PHP has the alternative of multiple inheritance called “traits.” It works similarly to multiple inheritances.

27. What is the main difference between a message$ and $$message?  
$message is used for regular variables and stores a fixed value. $$message is a reference variable where the value dynamically changes.

28. Why do we use Ksort in PHP? 
We use Ksort to sort an array in reverse order.

29. How is a password encrypted in PHP?
We can encrypt passwords using the hash algorithm. Functions used mostly in PHP are md5(), crypt(), and password_hash()

Pointer image icon

Intermediate PHP Interview Questions with Answers

intermediate interview questions PHP

30. How can you concatenate two strings in PHP?
For this, you would require a dot (.) operator, and you can write the following code:
 

<?php $string1=”Hello World“; $string2=”in PHP”; echo $string1 . ” ” . $string2; ?> 

The output of this will be: Hello World in PHP

31. What is the use of Memcache?

  • Firstly, Memcache significantly minimizes the load time of the database by reducing the number of database calls.  
  • Secondly, it improves the user experience with improved data access time.  
  • And thirdly, it increases the speed of the website by storing the object in dynamic memory. 

32. Write down the syntax to create an array for a group of items inside the HTML form.

<input name=”MyArray[]” />  <input name=”MyArray[]” />  <input name=”MyArray[]” />  <input name=”MyArray[]” />

33. Why are traits used in PHP  

PHP does not support multiple inheritances. A child class can only inherit from a single parent. Due to this, traits are used to minimize the limitation of single inheritance in PHP. It is a group of various methods that allow developers to reuse sets of methods. Below is an example of using multiple traits in PHP:  

<?php
trait message1 {
public function msg1() {
echo “OOP is fun! “;
}
}

trait message2 {
public function msg2() {
echo “OOP reduces code duplication!”;
}
}

class Welcome {
use message1;
}

class Welcome2 {
use message1, message2;
}

$obj = new Welcome();
$obj->msg1();
echo “<br>”;

$obj2 = new Welcome2();
$obj2->msg1();
$obj2->msg2();
?>
Source W3 School 

34. Explain the significance of PSR.
It is a PHP Standard Recommendation (PSR). A set of guidelines that ensures code consistency, collaboration within the community, and interoperability of projects in PHP.
 

35. How do you use comments in PHP?

Comments can be used in two different ways:

Single line: <?php
# This is a comment
echo “Single-line comment”;
?>

Multiple line: <?php
/*
This is
a
Multi-line
Comment
In PHP;
*/
echo “Multi-line comment”;
?>

36. Define Persistent Cookies.
It is a type of cookie stored on the user’s device that contains the details of the user’s sign-in information saved previously, preferences, and settings. To set the persistent cookie in PHP,  you can write the following code: 

setcookie (“user”, “Ansel Elgort”, time() + 3600 * 24 * 30); 

37. Name some of the popular content management systems built using PHP.

  • Magneto  
  • WordPress  
  • Joomla  
  • Durpal 

38. Write steps to execute a PHP script from the Command Line

  • Open your command-line window. 
  • Go to the directory where the PHP files are located. 
  • Run the PHP code using the php file_name.php command line. 
  • Now you need to start the server using this command: php -S localhost:port -t your_folder/. 

39. Can you show how to find duplicate email records in the user table?
SELECT u1.first_name, u1.last_name, u1.email FROM users as u1 

INNER JOIN ( 

SELECT email FROM users GROUP BY email HAVING count(id) > 1 

) u2 ON u1.email = u2.email;

40. What is the difference between mysql_fetch_array(), mysql_fetch_object(), and mysql_fetch_row()? 

  • mysql_fetch_array(): It fetches one row of data according to the result specified in the result identifier. And each result column stores an array offset.  
  • mysql_fetch_object(): It fetches the result row as an object. If there are no more rows to fetch, then it returns false.  
  • mysql_fetch_array(): It fetches the result row as a numeric array or associative array. 

41. Show how to establish a database connection in PHP.

<?php
$servername = “localhost”;
$username = “username”;
$password = “password”;

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
echo “Connected successfully”;
?>
SourceW3 School

42. How can we redirect page in PHP?

We can redirect pages in PHP using header functions.

By using the header function in PHP, we can send the raw HTTP header to the client.

Syntax for redirecting pages using header functions:

header( $header, $replace, $http_response_code )

<?php

header(“Location: http://www.redirect.com/another-page.php”);

exit();

?>

43. What is the Magic Method?

The magic method is the set of member functions available for all instances of the class. It is always defined within the class. The following are the magic methods:  

  • __construct()  
  • __destruct()  
  • __set()  
  • __get()  
  • __call()  
  • __toString()  
  • __sleep()  
  • __wakeup()  
  • __isset()  
  • __unset()  
  • __autoload()  
  • __clone()  

44. How does JavaScript interact with PHP?  

PHP, being a scripting language, can easily generate JavaScript variables and then execute them in the browser.

45. Write a simple program using the While Loop.  

my_qry = mysql_query(“SELECT * FROM `users` WHERE `u_id`=’1′; “);

while($result = mysql_fetch_array($my_qry))

{

echo $result[‘First_name’.].”<br/>”;

}

46. How does a client communicate with the web server?

The client can communicate with the server in two different ways:

•GET Method

•POST Method

•GET Method: <?php

if( $_GET[“name”] || $_GET[“age”] ) {

echo “Welcome “. $_GET[‘name’]. “<br />”;

echo “You are “. $_GET[‘age’]. ” years old.”;

exit();

}

?>

<html>

<body>

<form action = “<?php $_PHP_SELF ?>” method = “GET”>

Name: <input type = “text” name = “name” />

Age: <input type = “text” name = “age” />

<input type = “submit” />

</form>

</body>

</html>

•POST Method: <?php

if( $_POST[“name”] || $_POST[“age”] ) {

if (preg_match(“/[^A-Za-z’-]/”,$_POST[‘name’] )) {

die (“invalid name and name should be alpha”);

}

Echo “Welcome “. $_POST[‘name’]. “<br />”;

echo “You are “. $_POST[‘age’]. ” years old.”;

exit();

}

?>

<html>

<body>

<form action = “<?php $_PHP_SELF ?>” method = “POST”>

Name: <input type = “text” name = “name” />

Age: <input type = “text” name = “age” />

<input type = “submit” />

</form>

</body>

</html> 

47. How can we set infinite execution time in PHP?

We can do this by adding the set_time_limit(0) function to the beginning of a script.

48. How to create a text file in PHP?  

$filename = “/home/user/guest/newfile.txt”;

$file = fopen( $filename, “w” );

if( $file == false)

{

echo ( “Error in opening new file” ); exit();

}

fwrite( $file, “This is a simple testn” );

fclose( $file );

49. Can you show how to get an IP Address from the Client Machine?

function getRealIpAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’]))
{
$ip=$_SERVER[‘HTTP_CLIENT_IP’];
}
elseif (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’]))
{
$ip=$_SERVER[‘HTTP_X_FORWARDED_FOR’];
}
else
{
$ip=$_SERVER[‘REMOTE_ADDR’];
}
return $ip;
}

Pointer image icon

Advanced PHP Interview Questions with Answers

50. Write a syntax to open a file in PHP.

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

51. Write down the steps to create a database using PHP and SQL.

•First, you need to create a connection from PHP code to the MySQL server.

<?php

$server name = “localhost”;

$username = “username”;

$server name = “password”;

$conn = new mysql ($server name, $username, $passowrd);

if ($conn->connect_error)

{

die(‘Connection fail: ’ , $conn->connect_error);

•Once it is successful, write a SQL query for creating the database.

$sql = “CREATE DATABASE myDB”;

Now execute it.

52. How can we submit the form without a submit button? 

We can do this in three ways 

The first way is by using the JavaScript function in the OnClick event.  

E.g: document.form_name.submit()

The second way to do this is to use the header “location:page.php.”  

And third, using a hyperlink, a JavaScript function.  

53. Show how to start a session and modify a session in PHP

The following is the code to start the session:

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION[“favcolor”] = “green”;
$_SESSION[“favanimal”] = “cat”;
echo “Session variables are set.”;
?>
</body>
</html>

54. How to execute a Command Line from a PHP Script? 

  • You need to download PHP from the official website and extract the zip file to your preferred location. 
  • Once done, right-click on the “my computer icon” and select properties, then click Advanced System Settings. 
  • Now click “Environment Variable” under the system variable. There is a path for the environment variable; click on it.
  • If there is no path environment variable, click on new and specify it in the edit system variable.
  • C:php to the Environment Variable Path to access from the command line” 
  • Click Ok and close all the remaining windows. 

55. Write a code to validate the Email, Name, and URL. 
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = “”;
$name = $email = $gender = $comment = $website = “”;

if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
if (empty($_POST[“name”])) {
$nameErr = “Name is required”;
} else {
$name = test_input($_POST[“name”]);
// check if name only contains letters and whitespace
if (!preg_match(“/^[a-zA-Z-‘ ]*$/”,$name)) {
$nameErr = “Only letters and white space allowed”;
}
}

if (empty($_POST[“email”])) {
$emailErr = “Email is required”;
} else {
$email = test_input($_POST[“email”]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = “Invalid email format”;
}
}

if (empty($_POST[“website”])) {
$website = “”;
} else {
$website = test_input($_POST[“website”]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match(“/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i”,$website)) {
$websiteErr = “Invalid URL”;
}
}

if (empty($_POST[“comment”])) {
$comment = “”;
} else {
$comment = test_input($_POST[“comment”]);
}

if (empty($_POST[“gender”])) {
$genderErr = “Gender is required”;
} else {
$gender = test_input($_POST[“gender”]);
}
}
?>
SourceW3 School 

56. How can we upload files in PHP?

First, you must configure PHP by going to the file upload directives and setting it to ‘on’. And then you must create an HTML form so that the user can choose the file to upload. But there are a few more things to consider, such as using the method = “post” and the attribute: enctype=”multipart/form-data”. This will specify the content type to use while submitting the form. Without this, file uploads in PHP won’t work.

<?php
$target_dir = “uploads/”;
$target_file = $target_dir . basename($_FILES[“fileToUpload”][“name”]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST[“submit”])) {
$check = getimagesize($_FILES[“fileToUpload”][“tmp_name”]);
if($check !== false) {
echo “File is an image – ” . $check[“mime”] . “.”;
$uploadOk = 1;
} else {
echo “File is not an image.”;
$uploadOk = 0;
}
}
?>

57. Explain the Callback function.

It is a function that PHP developers can create themselves and pass to another function as an argument.

<?php

function thisFuncTakesACallback($callbackFunc)

{

echo “I’m going to call $callbackFunc!

“;

$callbackFunc();

}

function thisFuncGetsCalled()

{

echo “I’m a callback function!

“;

}

thisFuncTakesACallback( ‘thisFuncGetsCalled’ );

?>

58. What is the syntax of foreach loop?

?php

$colors = array(“blue”, “white”, “black”);

foreach ($colors as $value) {

echo “$value

“;

}

?>

59. Does PHP support typecasting?

Yes, the following are the types that PHP supports:  

  • (int), (integer): Cast to integer  
  • (bool), (boolean): Cast to boolean  
  • (float), (double), (real): Cast to float  
  • (string): Cast to string  
  • (array): Cast to array  
  • (object): Cast to object  

60. Write a code to create and retrieve a cookie.

<?php
$cookie_name = “user”;
$cookie_value = “John Doe”;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”); // 86400 = 1 day
?>
<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
echo “Cookie named ‘” . $cookie_name . “‘ is not set!”;
} else {
echo “Cookie ‘” . $cookie_name . “‘ is set!<br>”;
echo “Value is: ” . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
SourceW3 School 

Pointer image icon

Final Words

To master the PHP interview questions, focus on the basics and its syntax first. Once you become confident, you can gain hands-on experience by working on real-life projects and participating in a coding challenge. You can go through all of these questions and be prepared. But interview questions are always unpredictable and unexpected. It’s good to practice more questions related to PHP. So with this, we have come to the end of the PHP interview question for 2024. If you are a PHP Developer, then sign up with Olibr and land top global opportunities. 

Take control of your career and land your dream job!

Sign up and start applying to the best opportunities!

FAQs

You should have a clear understanding of the basic concepts, error handling, and syntax rules. Once you’re clear on the basic concept, you can move forward with the database questions. And then understand how cookies and sessions are used in PHP

PHP is mostly used in web development to build the backend of websites.

According to Payscale, developers who have 1-4 years of experience can earn up to $60K annually. For those who have 5 years of experience, it can go up to $73 annually.

To become a PHP developer, you need to have a good understanding of both basic and advanced concepts in PHP programming. You should also be familiar with configuring web servers like Nginx and Apache. Database connectivity is crucial in PHP, so you must be skilled in managing databases. In addition, having strong soft skills and familiarity with PHP frameworks will be beneficial in your role as a PHP developer.

 
 
 

You may also like

Leave a Comment