Essential PHP Interview Questions for Experienced Developers

Essential PHP Interview Questions for Experienced Developers

PHP Interview Questions for Experienced
PHP Interview Questions for Experienced

With this post, we have prepared the must-have list of PHP Interview Questions for Experienced developers.

PHP is still dominating the big market share in web application development. Experienced PHP developers are always in great demand for web development companies. In addition to our previous guide of PHP Interview Questions, we are providing another set of PHP Interview Questions for experienced developers.

This PHP Interview Questions for Experienced guide would help both organizations seeking expert PHP developers and candidates preparing for PHP developer interviews.

PHP Interview Questions for Experienced Developers

Q1). How to define a constant in PHP?

Answer:

A constant in PHP is a variable whose value is fixed throughout the PHP program or script. Unlike variables, the value of the constant can not be modified at runtime when the PHP script is running.

The PHP define() function is used to define a constant.

PHP constant example

For example, Lets create SYNC_FREQUENCY as a constant:
define(‘SYNC_FREQUENCY’, ’10’);

PHP Interview Questions for Experienced Developers.

Q2). What is the difference between PHP explode() and implode() functions?

Answer:

The PHP explode() function creates an array from a given string. The delimiter argument split the data argument into multiple elements. This function is safe to use with binary strings. The implode function will convert an array into a string. 

PHP Interview Questions for Experienced Developers

Syntax – array explode(string delimiter, string data)

PHP explode() function example:

<?
/*
** convert tab-delimited list into an array
*/
$data = “red\tgreen\tblue”;
$colors = explode(“\t”, $data);
// print out the values
for($index=0; $index < count($colors); $index++)
{
print(“$index : $colors[$index] <BR>\n”);
}
?>

The PHP implode() function is reverse of explode(). The PHP implode() functions is used to transform an array into a single string. The array elements are concatenated with the delimiter string separating them. To perform the reverse functionality, use
explode.

Syntax – string implode(array data, string delimiter)

PHP implode() example

<?
/*
** convert an array into a comma-delimited string
*/
$colors = array(“red”, “green”, “blue”);
$colors = implode($colors, “,”);
print($colors);
?>

Q3). How to redirect a page in PHP?

Answer:

In some situations, after performing data validations, you want to redirect the user to a new URL. For example, after a successful user login, you want to redirect the user to the User Dashboard page.

header(‘Location: https://www.techcluesblog.com/top-50-php-interview-questions-and-answers/’);
   exit();

Q4). What is difference between include() and require() in PHP?

Answer:

PHP include() function causes the PHP parser to open the specified .php file and execute it before doing further processing. The included file acts as a normal PHP script. Hence, the output text is sent directly to the browser

An interesting point to note is that we can specify either a local file or remote file present on a remote location. (http://, file://, etc). In that case, PHP parser will first fetch the remote file and execute it.

PHP include example: (PHP Interview Questions for Experienced Developers)

header.php

<?php
echo “<p>This PHP include example</p>”;
?>

Now, include header.php file in index.php file.
<html>
<body>

   <?php include ‘header.php’;?>

   <h1>Welcome Blogger!</h1>
   <p>PHP Interview Questions for Experienced Developers.</p>
   <p>PHP Interview Questions for Experienced Programmers.</p>

</body>
</html>

On the other side, PHP require() function is identical to include() function, but there is a big difference between PHP include and PHP require functions. When a file is included using include() function and suppose that file is not present, the PHP script will continue execution, it will not stop. Meaning that it treats this as a warning.

Whereas when the file is included using require() function and file is not present, PHP would throw an error and exit from the PHP script. Awesome PHP Interview Questions for Experienced Developers.

Q5). What is a static variable in PHP and how to use them?

Answer:

The PHP static variable is a special kind of variable that can retail value between function calls.

Normally, the non-static variable lost its value after the control returns from the function. So, the static variable retains its value even after leaving the function.

PHP static variables are created using static keyword. The static variable is initialized only once.

Syntax – static <variable>;

PHP static variable example:
<?php
function incrementNumber() {
   static $countNum = 0;
   $countNum++;
   print $countNum;
   print “<br />”;
}

incrementNumber();
incrementNumber();
incrementNumber();
?>

PHP static would produce the following output:
1
2
3

Here, note that count is initialized to 0 only once. PHP Interview Questions for Experienced

Q6). Does PHP support Object-Oriented-Programming concepts?

The earlier releases of PHP were a purely procedural language where you could define functions and concepts OOPs, Classes, and Objects was not introduced. Awesome PHP Interview Questions for Experienced Developers.

PHP evolved over the years and now from PHP 4, it starts supporting the concept of OOPs (classes and objects)
But, PHP is not pure and strong Object-Oriented programming language because of some limitations.

Q7). How to define a class in PHP and create objects?

A class in PHP is a logical abstraction of an object. It encapsulates the data and associated methods to access that data.

The data part is known as the properties of a class and functions that manipulate properties are called Methods.

And, an object is a variable of class type. So, in simple terms, a Class is just a definition of an object. PHP Interview Questions for Experienced

The PHP class keyword is used to define the new class.

PHP class example:
class BlogProject

{
public $comments;
public $last_visitor;
function update($comment, $visitor)

{
//function code
}
}

Create a class object in PHP. The PHP new keyword is used to create an object of a class:

$newBlog = new BlogProject;

The process of creating an object of a class is called – object instantiation.

Keep reading this Awesome PHP Interview Questions for Experienced Developers.

Q8). How to define a function in PHP? How to call the function in PHP?

Answer:

A function in PHP is a piece of code to perform a particular task. For example, user-defined sum() function to calculate the sum of two numbers, calculateSalary() to calculate the salary of an employee.

PHP functions help to organize the code that can be re-used later.

Use the function keyword to define a new user-defined function in PHP.

How to declare the function in PHP?

PHP function keyword followed by function-name is used to declare/define  a function:

function calCulateSalary($hra, $bonus)

{

   $basic = 40000;

   $salary = $basic + $hra + $bonus;

   return $salary;
}

Here, the user defined function calculateSalary() calculates and return the employee salary.

Q9). How to prevent XSS (Cross-Site-Scripting) attacks in PHP?

Answer:

The golden rule of preventing XSS attacks is not to trust any type of data traveling from client to server or any other source. Each and every bit of data must be validated to prevent XSS attacks.

To protect the integrity of data to be displayed to the client’s web browser, PHP developers should first escape the data before validations at the server side.

We ensure you that this Awesome PHP Interview Questions for Experienced Developers would help you crack interview.

This mechanism prevents the client web browsers from giving any unintended meaning to the data.

<?php
// escape the output before sending to client
echo “Your query: ” . htmlspecialchars($_GET[“MyQuery”]);

Use the PHP htmlententies() function to escape Escape all HTML output

Q10). How to pass variables to a new page when redirecting the user to the new URL?

Answer:

To pass variables to the new page, include them in the query string of the URL. Redirecting with query string variables.

PHP URL redirection example

header(‘Location: https://www.techcluesblog.com/?language=blue’);
exit();

This guide on PHP Interview Questions for Experienced Developers would boost your confidence level.

Q11). How to immediately stop the execution of PHP script?

Answer:

The PHP exit() function is used to stop the execution, print message, and terminate the script.

PHP exit() function example
<?php
   $url = “https://www.techcluesblog.com/”;
   fopen($url,”r”)
   or exit(“Unable to connect to $url”);
?>

Q12). What is a session in PHP?

Answer:

PHP provides strong user sessions management feature to develop stateful web applications. That means, at server-side web applications keep track of the website/application visitors.

Keeping the user tracking information becomes necessary when developing e-commerce, online banking, or portals.

The backbone of client/server communication HTTPS  – is the stateless protocol which does not maintain user state.

PHP provides the concept of sessions and associated function for user session management. PHP Sessions are focused on maintaining visitor-specific state between multiple requests.

By default, session data is stored in flat files in the server’s /tmp directory.

The PHP session_start() function is used to start and initialize the PHP session.

PHP session example
<?php
     // Start the session
     session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION[“num_visits”] = “1”;

echo “Session variables are set.”;
?>

</body>
</html>

You can bookmark this PHP Interview Questions for Experienced Developers guide for later use.

Q13).  How to check a datatype of a variable in PHP?

Answer:

PHP gettype() functions is used to get the data type.

Syntax – gettype ( mixed $var ) : string
Return – Returns the type of the PHP variable var.

PHP gettype() Possible values for the returned string are:

“boolean”
“integer”
“double” (for historical reasons “double” is returned in case of a float, and not simply “float”)
“string”
“array”
“object”
“resource”
“resource (closed)” as of PHP 7.2.0
“NULL”
“unknown type”

PHP gettype() example
<?php

$arData = array(1, 1., NULL, new stdClass, ‘foo’);

foreach ($arData as $value)

{
echo gettype($value), “\n”;
}

?>

Output

integer
double
NULL
object
string

Q14). How to delete a file in PHP?

Answer:

The PHP unlink() function can be used to permanently delete the given file form the system.

Syntax – unlink($file, context)

Here, the second parameter is optional.

Return – This function returns TRUE on success, or FALSE on failure.

PHP unlink() example

<?php
$fd = fopen(‘test1.html’, ‘a’);
fwrite($fd, ‘<h1>Hi Reader!</h1>’);
fclose($fh);

unlink(‘test1.html’);
?>

Here, the unlink function will delete the test1.html file from the system.

Q15). What is the use of following code snippet?

header(‘Location: https://www.techcluesblog.com’);

Answer:

PHP header() function is used to send back header to the client application.

Q16). How to count the number of array elements in PHP?

Answer:

To count the number of elements in an array in PHP, you can use PHP count() function.

This function returns the total number of elements in an array.

PHP count() example

<?php
$names = array(“Name1″,”Name2″,”Name3”);
echo count($names);
?>

Output: 3

Q17). How to upload a file in PHP?

Answer:

PHP provides a very simple interface for developers to upload text and binary files. PHP is capable of receiving file user uploads from any RFC-1867 compliant browser.

First of all, you have to enable file uploads in php.ini.

Look for file_uploads directive in php.ini file.

file_uploads = On

PHP file upload example

<!DOCTYPE html>
<html>
<body>

<form action=”validate_upload.php” method=”post” enctype=”multipart/form-data”>
Select file to upload:
<input type=”file” name=”fileToUpload” id=”fileToUpload”>
<input type=”submit” value=”Upload file” name=”submit”>
</form>

</body>
</html>

Q18). What is the use of $_REQUEST variables in PHP?

Answer:

$_REQUEST is a global variable in PHP used to retrieve user data after the HTML form submitted to the server. This is a superglobal variable means that it’s available in all PHP scripts in an application.

It is by default an associative array which holds the contents of $_POST and $_GET variables.

PHP $_REQUEST example:
<?php

switch($_SERVER[‘REQUEST_METHOD’])
{
   case ‘GET’: $the_request = &$_GET; break;
   case ‘POST’: $the_request = &$_POST; break;
   .
   . // Etc.
   .
    default:
}
?>

Q19). How to concatenate strings in PHP?

Answer:

PHP concatenate operator “.” is used to concatenate two given strings into one resultant string.

PHP concatenate strings example
<?php
$str1 = “Hello “;
$str2 = $str1 . “World!”;

$str3 = “Hello “;
$str3 .= “World!”; // now $a contains “Hello World!”
?>

Q20). Write the PHP functions to remove whitespaces from the string?

Answer:

Sometimes, it becomes necessary to remove extra white spaces (both from left and right) of a given string.

For example, you want to clean the user input before it is validated.

There are the following PHP functions to remove white spaces:

trim() – removes whitespaces from both left and right of the string.
Syntax – trim ( string $str [, string $character_mask = ” \t\n\r\0\x0B” ] ) : string

ltrim() – Removes whitespaces from the beginning of string i.e left

rtrim() – removes whitespaces from the end of string
Syntax – rtrim ( string $str [, string $character_mask ] ) : string

The return value of all these functions would be string with whitespaces removed.

PHP trim() example
<?php
$str = ” Hello World! “;
echo “Without triming white-spaces: ” . $str;
echo “<br>”;
echo “After triming white-spaces: ” . trim($str);
?>

Q21). What is a permanent or persistent cookie in PHP?

Answer:

There are two types of Cookies in PHP:
1. Temporary Cookie in PHP
By default, a temporary cookie is created and stored in the client’s browser memory. So, when the browser is closed, the temporary cookie will also be removed from the browser memory, that’s why its called temporary cookie.

2. Persistent Cookie in PHP
A persistent cookie in PHP is stored in the client browser permanently. It retains the vale even after the client browser is closed. Persistent cookies are used to keep users long-term information.

Temporary cookies are more secure than persistent cookies. This is because persistent cookies are stored in a file that the user can open.

How to create a persistent cookie in PHP
PHP setcookie() function is used to create a permanent cookie and send along with HTTP response to the user.

Syntax – setcookie(name,value,expire,path,domain,secure,httponly);

PHP setcookie() example:
<?php
   $value = ‘This is my test cookie!’;

   setcookie(“PersCookie”, $value);
   setcookie(“PersCookie”, $value, time()+3600); /* expire in 1 hour */
?>

Note: Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically be decoded and assigned back to a variable by the same name as the cookie name. 

Q22). What is the GD library in PHP?

Answer:

PHP GD library is a Graphics Drawing library in PHP which provides a rich set of functions to create, modify, customize and manipulate images in PHP applications.
It supports JPG, PNG, GIF and more.

Q23). What is PDO in PHP?

Answer:

PDO stands for PHP Data Objects.

PHP PDO is an extension which provides a lightweight, simple, and flexible interface for interacting with the databases.

In simple terms, PDO is an abstract layer which provides a common interface between the developer and underlying database. 

So, the same interface can be used to communicate with any type of database. 

Connect to DB using PHP PDO

PHP PDO Example
<?php

$username = “testuser”;

$password = “tempass”;

//Create new connection request
$dbCon = new PDO(‘mysql:host=localhost;dbname=test’, $username, $password);
// use the connection here
$queryRes = $dbCon->query(‘SELECT * FROM foo’);

$queryRes = null;
$dbCon = null;
?>

Q24). What are the traits in PHP and how to implement traits in PHP?

Answer:

Since PHP5.4.0 onwards, PHP has introduced the concept of PHP Traits for code reusability. PHP trait is similar to an abstract class in PHP that can be instantiated but more convenient than single inheritance.

It was introduced to counter some limitation of single inheritance in PHP.

Basically, traits are used to compose multiple objects into a single unit and provides a better interface than inheritance.

PHP trait example
<?php
   trait ezcReflectionReturnInfo

  {
      function Fun1() { /*1*/ }
      function Fun2() { /*2*/ }
  }

Q25). What is a Composer in PHP? when to use it?

Answer:

Composer in PHP is a very powerful package manager tool. PHP composer is used to install, uninstall, update new packages.

To install Composer, you first need to download the installer file and send it to PHP.

The composer is very helpful for developers to manage third-party packages in PHP based projects. 

Follow this post to revise basic PHP Interview Questions.

Conclusion:

We hope this guide on PHP Interview Questions for Experienced must have helped to improve your existing PHP knowledge base. Ultimately, this guide will help you to boost your confidence level before sitting in the PHP Interview.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *