PHP Interview Questions and Answer to Refer for Quick Preparation

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Here, we have the latest PHP interview questions for candidates who are actively looking for a job in PHP and determined to succeed. I have picked questions which are relevant for all levels starting from freshers to experienced.

Demand for PHP developers is growing consistently. And many IT companies are ready to offer a decent package for the right candidates. However, a lot of freelancing or contract options are also available for them. Large sites like Facebook, Baidu, Wikipedia, VK, and even Twitter are also using PHP for powering their backend services.

Despite so many opportunities, you should prepare hard without being complacent. In this post, we’ve added all relevant PHP interview questions covering most of the important areas of web development. So read them thoroughly, save time, and prepare fast.

Success in a technical interview would not only depend on how much you know but also on what should you know.

PHP Interview Questions and Answers.

Q-1. What does PEAR signify in PHP?

Answer.

PEAR is an acronym for PHP Extension and Application Repository. It was Stig S. Bakken who introduced it in 1999 with following features.

  • A structured library of open-sourced code for PHP users.
  • Simple code distribution and package management.
  • A standard style for code written in PHP.
  • The PHP Foundation Classes (PFC).
  • The PHP Extension Community Library (PECL).
  • A website, mailing lists, and download mirrors to support the PHP/PEAR community. Thus, PEAR is a community-driven project with the <PEAR Group> as its governing body.
  • It provides a command-line interface that can come into use for installing the packages on demand.

Q-2. What is the difference between $name and $$name?

Answer.

$name is a variable whereas $$name is a reference to the variable.

Let’s see an example.

$name "Welcome";

$Welcome "To";

$To "TechBeamers";

echo $name;
/*prints Welcome*/
echo $$name;
/*prints To*/
echo $$$name;
/*prints TechBeamers*/

This code sample prints the following message <WelcomeToTechBeamers>.

Q-3. How do you embed PHP code in an HTML page?

Answer.

In an HTML page, all PHP code must enclose within either of the three special markup tags recognized by the PHP Parser.

  • <?php PHP code goes here ?>
  • <? PHP code goes here ?>
  • <script language=”php”> PHP code goes here </script>

Amongst these <?php…?> is the most commonly used tag.

We can chain as many statements as required separating them with semicolon as shown below.

<?php

  echo "Hello World";

  echo "A second statement";

?>

Q-4. What is the name of scripting engine of PHP?

Answer.

ZEND Engine 2 is the name of the scripting engine that powers PHP.

Q-5. What is the difference between the GET and POST methods?

Answer.

Following are the key differences between <GET> and <POST>.

  • GET Method.

    • It submits all the Name-Value pairs as a query string in the URL.
    • This method is not secure and reveals the data transmitted with the URL.
    • The allowed length of the GET string should not exceed 2048 characters.
    • If the Form tag does not contain any method name, GET will take over as default.
    • The payload data is in the text format. It accepts only ASCII values.
    • GET is beneficial for performing data retrieval operation.
  • POST Method.

    • It submits all the Name-Value pairs in the Message Body of the request.
    • Unlike the GET, Post method is secure as the Name-Value pairs do not appear in the location bar of the web browser.
    • Since the payload gets encoded into the request, so it doesn’t show up as part of the URL.
    • There is no restriction on the length of the string (i.e. the amount of data transmitted).
    • In case, the POST method is in use and page refresh happens at the same time, then a prompt will occur before processing the request.
    • If the service associated with the processing of a form has side effects (for example, modification of a database or subscription to a service), the method should be POST.
    • It has no restriction on data usage and permits binary data also.
    • POST is beneficial for performing both insert and update operations.

Q-6. What are Magic functions in PHP?

Answer.

They are special PHP functions that start with a double underscore <__>. None of these are stand-alone. And it is mandatory to define them inside a Class.

Below are some facts about the Magic functions in PHP.

  • It is the programmer who provides their definition instead of PHP. By allowing the programmer to provide the definition, it enables him to achieve powerful things using these Magic functions.
  • PHP does not allow to call them directly from the code. Instead, the call happens indirectly.

Let’s see an example.

class Animal {
   // height of animal 
   public $height;
   // weight of animal
   public $weight;
   // code
   public function __construct($height, $weight)
   {
      $this->height = $height;  //set the height instance variable
      $this->weight = $weight; //set the weight instance variable
   }
}

Now, if we instantiate the Animal Class using the following line of code.

Animal obj = new Animal(6, 150);

It will automatically call the <__construct()> function and create an object obj, of the Animal class, with its height as 6 and weight as 150.

Here is the list of some powerful magic functions supported by PHP.

__construct() , __destruct() , __call() , __callStatic() , __get(), __set() , __isset() ,__unset()

, __sleep() , __wakeup(), __toString() , __invoke() , __set_state() , __clone().

 

Q-7. What is a .htacces file in PHP?

Answer.

The <.htaccess> is a configuration file used on the servers to run the Apache Web Server software. If this file is present in the directory, then the Apache Web Server will load it into memory and execute.

It acts as a powerful tool to alter the configuration of the Web Server software by enabling/disabling the additional functionality and features that it offers.

These include –

  • The redirection feature like an occurrence of 404, file not found.
  • More advanced functions such as content password protection or image hotlink prevention.

 

Q-8. How can we display the output directly to the browser?

Answer.

In order, to display the output directly to the browser, we have to use the special tags <?= and ?>.

Q-9. What are the different types of errors in PHP?

Answer.

There are essentially three types of errors in PHP.

  • Notices.

    • These are small, non-critical errors that PHP encounters while executing a script. For instance, accessing a variable that is not defined. By default, PHP does not display these errors to the user. However, the default behavior can be modified.
  • Warnings.

    • These are more severe errors, like attempting to include() a file which does not exist. By default, PHP displays these errors to the user. They do not result in script termination.
  • Fatal Errors.

    • These are critical errors. For example, instantiating an object of a non-existent class, or calling a non-existent function. These errors result in immediate termination of the script. PHP’s default behavior is to display them to the user when it occurs.

 

Q-10. What is the maximum filesize that PHP allow to upload? How can we increase it?

Answer.

The standard limit in PHP to upload a file is 2MB. However, we can change this value by making modifications in the php.ini file. We have to alter the value of upload_max_filesize and restart all the services.

Q-11. What is a final class in PHP?

Answer.

The final class is a unique object-oriented concept which prohibits a class from being inherited. We can use it to protect the methods of the base class from getting overridden by the child classes.

Final Class Example.

final class baseclass
{
   public function mymethod()  {
      echo  "base class method";
   }
}

class derivedclass extends baseclass
{
   public function mymethod() {
      echo   "derived class method";
   }
}

$c = new derivedclass();
$c->mymethod();

In the above example, we’ve kept the base class as final to prevent it from being derived. However, the second class in the example is trying to extend the base which will cause a compile time error.

 

Q-12. What is the difference between include() and require()?

Answer.

The <include()> function throws a warning when file not found error occurs. But the script continues to execute till its end. Let’s see an example.

<?php
      include("filename.php");
      echo "Welcome";
?>

In the above example, if the file not found error occurs, the code will lead to a warning and print <Welcome>. It is because a warning in PHP neither stops the execution of the script nor does it blocks the echo command.

The <require()> function gives a fatal error if the specified file is not found and also stop the execution of the script. Let’s see an example.

<?php
      require("filename.php");
      echo "Welcome";
?>

The above code will throw a fatal error and stop the script. Even the echo command will also not run in this case.

Q-13. What is the use of var_dump in PHP?

Answer.

The var_dump function takes one or more variables as arguments and returns structural information about their types and values. It has the following syntax.

var_dump(variable1, variable2,.....variablen);

Here is an example.

<?php
       $m=3.1;
       $n=true;
       var_dump($m, $n);
?>

Above code displays the following output.

float(3.1)
bool(true)

 

Q-14. What are the differences between echo() and print() methods?

Answer.

Following are the key differences between echo() and print() statements.

  • Echo.

    • It can accept multiple expressions.
    • Since it does not return any value, so responds a bit faster.
    • Echo statement displays the output on the user screen. Its syntax supports using echo with or without parentheses.
    • Multiple arguments are allowed if separated with <,>.
    • It doesn’t return any value.
  • Print.

    • It cannot accept multiple expressions.
    • Returning a value makes it a little slower than the echo.
    • Print statement displays the output on the user screen. Its syntax supports using print with or without parentheses.
    • Multiple arguments are not allowed.
    • Interestingly, it will always return the value 1.

 

Q-15. What are visibility keywords in PHP?

Answer.

We can set the visibility of a Property or Method by prefixing the declaration with the following keywords public, protected, or private.

  • Public specifier signifies that the members are accessible from everywhere within your application.
  • Protected specifier indicates that the members are accessible from within the class, the one that inherits it and from the parent as well.
  • Private specifier restricts that the members should only be accessible from within the class.

 

Q-16. What is the importance of PHP function htmlentities()?

Answer.

The <htmlentities()> function ensures that the text is correctly printed into HTML. It does this by converting any character that might be read as part of the HTML markup so that it gets displayed, rather than parsed.

For example, the < and > characters have specific meaning in HTML. They are used as start and end delimiters for HTML tags. If we wish to print them as a part of the text (as the “less-than” and “greater than” characters) rather than getting parsed as a part of the HTML markup, we need to convert them into HTML entities.

HTML entities are special character sequences that represent characters, so they can be printed into the HTML without messing it up. Like HTML entities for the < and > characters look like: “&lt;” and “&gt;”.

The htmlentities() function takes a normal string and converts any character like < and > into their respective HTML entity.

Here is the prototype of this function.

htmlentities(string, flags, character-set, double_encode)

Let’s take an example.

<?php
   $str = '<a href="https://www.dhanjivpandey.com">Go to dhanjivpandey.com</a>';
   echo htmlentities($str);
?>

The HTML output of the above code above will look like the one shown below.

&lt;a href=&quot;https://www.dhanjivpandey.com&quot;&gt;Go to dhanjivpandey.com&lt;/a&gt;

However, the browser will render the above code in the following style.

<a href="https://www.dhanjivpandey.com">Go to dhanjivpandey.com</a>

 

Q-17. What is Type juggle in PHP?

Answer.

In PHP, mentioning the type of the variable is not required on declaring a variable. The data type is determined implicitly, by the value/context of the variable. If we assign an integer value to a variable $num, then it becomes of type integer, implicitly. If we assign a string value to the variable $str, it becomes of type string.

Let’s take an example.

$num3 = $num1 + $num2

Here, if $num1 is an integer, PHP also treats $num2 and $num3 as integers.

 

Q-18. What is the use of header() function in PHP?

Answer.

The header() function sends a raw HTTP header to the client browser. Its rule is to call this function always, before sending the actual output.

For example, we don’t print any HTML element, before using header() function.

Q-19. What is PHP filter and why is it used? Also, list down different PHP filter functions.

Answer.

The primary use of PHP filter is to validate the data coming from different sources.

  • User input from a form
  • Cookies
  • Web services data
  • Server variables
  • Database query results

Filtering is an important feature for a web application to validate and sanitize the data coming from insecure sources. And the PHP filter extension has many of the functions required for checking user input which makes data validation, easier and quicker.

Following are a few different filter functions supported by PHP.

PHP filter Functions.

  • <filter_has_var()>
    • Checks if a variable of specified input type exists.
  • <filter_id()>
    • Returns the ID number of a specified filter.
  • <filter_var_array()>
    • Get multiple variables and filter them.
  • <filter input()>
    • Get input from outside the script and filter it.
  • <filter_input_array>
    • Get multiple inputs from outside the script and filters them.
  • <filter_list()>
    • Returns an array of all filters it supports.
  • <filter_var()>
    • Get a variable and filter it.

Q-20. How can we get all the properties of a browser in PHP?

Answer.

We can get the browser properties by using following code snippet.

<?php
   $_SERVER ['HTTP_USER_AGENT'];
?>

Q-21. What is a Session in PHP? How does PHP manage the lifecycle of a session?

Answer.

Sessions are data structures which provide a way to store user specific data and associates it with a unique session ID. However, PHP sessions also solve the following problems.

Problem-1.

Most websites use cookies, a standard way to cache session data. However, using them poses a few security issues. Since they get stored locally on user’s computer, so it becomes easier for an attacker to modify the cookie and inject malicious data.

Problem-2.

Whenever a browser loads a web page, it also offloads the cookie information to the server. Let’s consider a scenario where we have five cookies, each of size 4KB. In this case, the browser will send 20 KB of data to the server. And this process will repeat every time the user views the web page affecting the performance of the site.

Solution.

PHP addresses both of the above issues as it stores session data on the server instead of holding it on the user’s computer. Each session gets a unique session ID known as SID. This identifier links each user with his information like emails, posts, etc. available on the server.

A session creates a file in a temporary directory on the server to cache the registered session variables and their values. This data will be accessible to all pages on the site during that stay.

PHP uses a php.ini file to get hold of the server settings. This file also specifies the location of the session file under the <session.save_path>. The developers can make sure that this setting points to a correct value before using the session variable.

PHP Session Lifecycle.

While building up a session following events happen.

1. PHP generates a unique identifier corresponding to the session. It is a random string of 32 hexadecimal numbers such as “c69dc153f003406b9a0242ad4c505baa”.

2. A cookie named as PHPSESSID get pushed to the user’s computer. It carries the unique session identification string.

3. Simultaneously, the PHP engine creates a file for every new session at the designated location. It bears the name of the unique identifier prefixed by <sess_>.

e.g. sess_c69dc153f003406b9a0242ad4c505baa.

4. When PHP gets a request from the browser or a client to access the session variable, it retrieves the session string from the PHPSESSID cookie. Consequently, it looks up in the temporary directory for the file bearing the session ID string.

5. A session comes to an end if the user decides to close the browser. However, the server could also terminate it after a certain inactivity period.

 

Q-22. What does accessing a class via “::” means?

Answer.

<::> operator allows accessing static methods that do not require to initialize the object. Its name is Scope Resolution Operator.

 

Q-23. How can we register the variables into a session?

Answer.

In order, to register a variable into the session, we must start the session by using the command.

session_start();

To assign a value to the variable with name <myvar>, we use the global variable <$_SESSION>.

$_SESSION['myvar'] = "value";

Let’s see the complete example.

<?php
/*
 * PHP Session - Register / Unregister session variables 
 */

//start the session
session_start();

//if not exists, ads the myvar variable into the session array
if (!isset($_SESSION['myvar']))
    $_SESSION['myvar'] = "value";

//echo the myvar session variable
echo "The myvar variable value is : ".$_SESSION['myvar'];

//unset the myvar session variable
unset($_SESSION['myvar']);
?>

 

Q-24. How can we destroy a session in PHP?

Answer.

First of all, you should make a judgment when to destroy a session in PHP. However, here are the three possible ways to close a session gracefully.

1. If there is only a single session and you want to delete its value, then calling the <unset()> function would be enough.

<?php
session_start();
// Destroy a particular session variable.
unset($_SESSION['myvar']) ;
?>

2. If you want to clear all session variables (i.e. $_SESSION array), then call the <session_unset()> function.

<?php
session_start();
// Frees all session variables.
session_unset();
?>

Please note that session_unset() function only reset the local $_SESSION variable instance but not the data inside the session storage.

3. The commands in the previous points only affect the $_SESSION variable or its values but leave the part in the session storage as is. However, there are cases when you have to remove all data bind to a session.

For example.

If a user logs out, then he won’t need the session anymore.

In such case, you should call the session_destroy() function. It destroys the session data cached inside the persistent storage (i.e. removes the session file from the file system).

<?php
// Removes all data registered to a session.
 session_destroy() ;
 ?>

 

Q-25. What is the difference between implode() and explode() function?

Answer.

Implode() Function.

The purpose of <implode()> is to join the elements of an array using a string delimiter. The resulting string acts as a return value for the function, which gets stored in a variable.

<Array to String> is the most appropriate phrase which helps to remember about implode function. Let’s see an example.

Suppose we have following array.

$arr = Array ("A", "E", "I", "O", "U");

Following is the command to combine it into a single string after applying the separator ‘-‘ between every element of the array.

$str = implode("-", $arr);

After executing the above code, the resulting string variable, $str will contain the following value.

A-E-I-O-U

Syntax for <implode()> is as follows.

implode(separator, array)

Explode() Function.

This function allows us to break a string into smaller text, where each break occurs at the same symbol. This symbol is known as the delimiter. By using the explode command, we create an array from a string.

Thus, an explode() function breaks a string into an array, however, the implode function returns a string from the elements of an array.

Let’s take an example having a string.

$str = "A E I O U";

Now, to make each alphabet as an element of an array, so that we can access it individually, we use the following code.

$arr = explode(",", $str);

The above code breaks the string $str based on separator ‘,’ and put the resulting array in variable $arr.

Array(
[0] => A
[1] => E
[2] => I
[3] => O
[4] => U
)

It is equivalent to the following.

$arr = Array ("A", "E", "I", "O", "U");

Syntax for explode() is as follows.

explode (separator, string, limit)

 

Q-26. How will you redirect a web page to another page using PHP?

Answer.

Following is the piece of code which redirects a web page to another page.

header("Location:url_of_the_page_to_redirect.php");
exit();

 

Q-27. What is the difference between <strstr()> and <stristr()> function in PHP?

Answer.

The <strstr()> function.

This function locates the first occurrence of a string.

It has the following syntax.

strstr ($string, string)

Let’s take an example to understand it better.

<?php
$email_id = 'meenakshi@gmAil.com';
$domain_name = strstr($email_id, 'A');
echo $domain_name;
?>

// Output: Ail.com

The <stristr()> function.

It locates the first occurrence of a string. The search here is case-insensitive.

Syntax:

stristr ($string, string)

Let’s take an example to understand it better.

<?php
$email_id = 'meenakshi@gmAil.com';
$domain_name = strstr($email_id, 'A');
echo $domain_name;
?>

Output: akshi@gmAil.com

If we want to return the other part of the string, then we need to write the code as.

<?php
$email_id = 'meenakshi@gmAil.com';
$domain_name = strstr($email_id, 'A', TRUE);
echo $domain_name;
?>

Output: meen

 

Q-28. How will you enable error reporting in PHP?

Answer.

Enabling the error messages, play a vital role in beginning the debugging process as it helps by locating the exact line that is producing the error and we can also determine if the script is working correctly.

In PHP, we use the <error_reporting> function, to turn on error reporting for a particular file. The other way is to enable error reporting for all the files at the web server by editing the php.ini file.

The most appropriate way to write error reporting function in PHP.

This function establishes the error reporting criteria at runtime. Since PHP has several levels of reportable errors, this function sets the desired level for the duration our script executes. It is desirable to add it in the beginning. So we can place the code immediately after the opening of the “<?php” tag.

PHP provides various options for enabling error reporting. Let’s get more clarity on this topic with the below code snippet.

<?php

//Disable all error reports
error_reporting(0);

//Enable basic runtime errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

//Allow E_NOTICE to catch uninitialized variables or variable name
//or misspellings
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

//Allow all PHP errors
error_reporting(-1);

//Allow all PHP errors
 error_reporting(E_ALL);

//Alternate way to allow all errors in PHP
ini_set('error_reporting', E_ALL);
?>

Display Errors in PHP.

The <display_error> setting determines whether errors get printed on the screen or hidden from the user.

It gets used in conjunction with the error_reporting function as shown in the example below.

ini_set('display_errors',1);
error_reporting(E_ALL);

Modify the php.ini file.

If we want to see error reports for all our files, then just go to the web server and add the following option in the php.ini file for the website.

error_reporting=E_ALL

The php.ini file is the default configuration file for running applications that use PHP. By placing the above option in the php.ini file, we are requesting error messages for all the PHP scripts.

 

Q-29. How do you send an email using PHP?

Answer.

Firstly, PHP requires doing some settings in php.ini file. For this open the php.ini file available in </etc/ directory> and find the section with heading [mail function].

Windows users have to define two directives, the first is SMTP, that indicates the email server address of the user. Whereas the second directive is sendmail_from, that represents the user’s own email address.

Configuration for Windows is as follows.

[mail function]
; For Win32 only.
SMTP = smtp.secureserver.net

; For win32 only
sendmail_from = dhanjivpandey.com

Whereas the Linux users, need to define the location of their send email application. The sendmail_path directive contains the definition for the path and any desired switches.

; For Unix only
sendmail_path = /usr/sbin/sendmail -t -i

Now, we are ready to send an email. PHP uses, mail() function to send an email. The function definition contains three mandatory arguments that are the recipient’s email address, the subject of the message and the actual message. Additionally, there are two other parameters also, which are optional. Following is the syntax.

mail function Syntax.

mail(to, subject, message, headers, parameters);

Here is the description for each of the parameters.

<to>

It’s mandatory. It contains the receivers/receiver of the email.

<subject>

Its presence is mandatory. This parameter represents the subject of the email. It cannot contain any newline characters.

<message>

It is mandatory. It represents the actual message that has to be transmitted. Each line should use an LF (\n) to separate it with other. The number of characters in each line should not exceed a count of 70.

<headers>

It’s optional. It defines additional headers like From, Cc, and Bcc. PHP makes the use of CRLF(\r\n) to separate these headers.

<parameters>

Its presence is optional and defines an additional parameter to the send mail program.

As soon as the mail function gets called, PHP makes an attempt to send the email. It returns true if it succeeds in sending the mail else it returns false.

Let’s see a sample code to send an email.

Send mail example.

<?php
// the message
$msg = "First line of text\nSecond line of text";

// use wordwrap() if lines are longer than 70 characters
$msg = wordwrap($msg,70);

// send email
mail("someone@example.com","My subject",$msg);
?>

 

Q-30. What are Superglobals in PHP?

Answer.

Superglobals are specially-defined array variables in PHP that make it easy for the user to get information about a request or its context. This data can come either from different URLs, HTML forms, cookies, sessions, and the Web server itself. They are named as Superglobals, because they are always accessible, regardless of the scope, that is, you can access them from any function, class or file without having to do anything special. PHP provides following superglobals.

$_GET

It represents the data forwarded to the PHP script in an URL. It applies to URLs that are directly accessible (e.g., http://www.example.com/page.php?id=2) and also to form submissions that use the GET method.

$_POST

It represents the data forwarded to the PHP script via HTTP POST. It is a form that includes a method POST.

$_COOKIE

It represents the data available to a PHP script via HTTP cookies.

$_REQUEST

It is a combination of $_GET, $_POST, and $_COOKIE.

$_SESSION

It represents the data available to a PHP script that was earlier, stored in a session.

$_SERVER

The $_SERVER Superglobal represents the data available to a PHP script, from the Web server itself.

$_ENV

It represents the data available to a PHP script from the environment in which PHP is running.

$_FILES

It represents the data available to a PHP script from HTTP POST file uploads. Using $_FILES is currently the most preferred way to handle uploaded files in PHP.

$GLOBALS

It stores all variables with global scope. It includes all of the above. Unlike the other Superglobals, $GLOBALS is part of PHP from the very beginning (PHP 3).

Q-31. What is the difference between unlink and unset function in PHP?

Answer.

<unlink()> function is useful for file system handling. We use this function when we want to delete the files (physically). Let’s see a sample code.

<?php
$xx = fopen('sample.html', 'a');
fwrite($xx, '<h1>Hello !!</h1>');
fclose($xx);

unlink('sample.html');
?>

unset() function performs variable management. It makes a variable undefined. Or we can say that unset() changes the value of a given variable to null. Thus, in PHP if a user wants to destroy a variable, it uses unset(). It can remove a single variable, multiple variables, or an element from an array. Let’s see a sample code.

<?php
$val = 200;
echo $val; //Out put will be 200
$val1 = unset($val);
echo $val1; //Output will be null
?>
<?php
unset($val);  // remove a single variable
unset($sample_array&#91;'element'&#93;); //remove a single element in an array
unset($val1, $val2, $val3); // remove multiple variables
?>

Q-32. What are PHP Traits?

Answer.

It is a mechanism that allows us to do code reusability in single inheritance language, such as PHP. Its structure is almost same as that of PHP class, just that it is a group of reusable functions. Despite having same name and definition, they appear in several classes, each one having a separate declaration leading to code duplicity. We can group these functions and create PHP Traits. The class can use this Trait to include the functionality of the functions defined in it.

Let’s take an example, where we create a Message class.

class Message
{
}

Let say there exists a class Welcome.

class Welcome
{
    public function welcome()
    {
        echo "Welcome","\n"
    }
}

To include its functionality in Message class, we can extend it as.

class Message extends Welcome
{
}

$obj = new Message;
$obj->welcome();

Let’s say there exists another class named Goodmorning.

class Goodmorning
{
    public function goodmorning()
    {
        echo "Good Morning","\n";
    }
}

We cannot include the functionality of the Goodmorning class in Message class, as PHP does not support Multiple Inheritance. Here, PHP Traits comes into the picture. Let’s see how Traits resolve the issue of Multiple Inheritance for Message class.

Example.

trait Goodmorning
{
    public function goodmorning()
    {
        echo "Good Morning","\n";
    }    
}

trait Welcome
{
    public function welcome()
    {
        echo "Welcome","\n";
    }
}    

class Message
{
    use Welcome, Goodmorning;
    public function sendMessage()
    {
        echo 'I said Welcome',"\n";
        echo $this->welcome(),"\n";

        echo 'and you said Good Morning',"\n";
        echo $this->goodmorning();
   }
}

$o = new Message;
$o->sendMessage();

It produces the following output.

I said Welcome
Welcome
and you said Good Morning
Good Morning

Q-33. How can we display the correct URL of the current webpage?

Answer.

<?php
echo $_SERVER['PHP_SELF'];
?>

Q-34. Why we use extract() in PHP?

Answer.

The extract() function imports variables into the local symbol table from an array. It uses variable names as array keys and variable values as array values. For each element of an array, it creates a variable in the current symbol table.Following is

Following is the syntax.

extract(array,extract_rules,prefix)

Let’s see an example.

<?php
$varArray = array("course1" => "PHP", "course2"  => "JAVA","course3" => "HTML");
extract($varArray);
echo "$course1, $course2, $course3";
?>

Q-35. What is the default timeout for any PHP session?

Answer.

The default session timeout happens in 24 minutes (1440 seconds). However, we can change this value by setting the variable <session.gc_maxlifetime()> in [php.ini] file.

Q-36. What is autoloading classes in PHP?

Answer.

With autoloaders, PHP allows the last chance to load the class or interface before it fails with an error.

The spl_autoload_register() function in PHP can register any number of autoloaders, enable classes and interfaces to autoload even if they are undefined.

<?php
spl_autoload_register(function ($classname) {
    include  $classname . '.php';
});
$object  = new Class1();
$object2 = new Class2(); 
?>

In the above example we do not need to include Class1.php and Class2.php. The spl_autoload_register() function will automatically load Class1.php and Class2.php.

Q-37. What are different ways to get the extension of a file in PHP?

Answer.

There are following two ways to retrieve the file extension.

1.  $filename = $_FILES[‘image’][‘name’];

$ext           =  pathinfo($filename, PATHINFO_EXTENSION);

2. $filename = $_FILES[‘image’][‘name’];

$array         = explode(‘.’, $filename);

$ext             = end($array);

Q-38. What is PDO in PHP?

Answer.

PDO stands for <PHP Data Object>.

  • It is a set of PHP extensions that provide a core PDO class and database, specific drivers.
  • It provides a vendor-neutral, lightweight, data-access abstraction layer. Thus, no matter what database we use, the function to issue queries and fetch data will be same.
  • It focuses on data access abstraction rather than database abstraction.
  • PDO requires the new object oriented features in the core of PHP 5. Therefore, it will not run with earlier versions of PHP.

PDO divides into two components.

  • The core which provides the interface.
  • Drivers to access particular driver.

Q-39. What does the presence of operator ‘::’ represent?

Answer.

It gets used to access the static methods that do not require initializing an object.

Q-40. How to get the information about the uploaded file in the receiving Script?

Answer.

Once the Web server receives the uploaded file, it calls the PHP script specified in the form action attribute to process it.

This receiving PHP script can get the information of the uploaded file using the predefined array called $_FILES. PHP arranges this information in $_FILES as a two-dimensional array. We can retrieve it as follows.

  • $_FILES[$fieldName][‘name’] – It represents the file name on the browser system.
  • $_FILES[$fieldName][‘type’] – It indicates the file type determined by the browser.
  • $_FILES[$fieldName][‘size’] – It represents the size of the file in bytes.
  • $_FILES[$fieldName][‘tmp_name’] – It gives the temporary filename with which the uploaded file got stored on the server.
  • $_FILES[$fieldName][‘error’] – It returns the error code associated with this file upload.

The $fieldName is the name used in the <input type=”file” name=”<?php echo $fieldName; ?>”>.

Q-41. What is the difference between Split and Explode functions for String manipulation in PHP?

Answer.

Both of them perform the task of splitting a String. However, the method they use is different.

The split() function splits the String into an array using a regular expression and returns an array.

For Example.

split(:May:June:July);

Returns an array that contains May, June, July.

The explode() function splits the String using a String delimiter.

For Example.

explode(and May and June and July);

Also returns an array that contains May, June, July.

Q-42. What is the use of ini_set() in PHP?

Answer.

PHP allows the user to modify some of its settings mentioned in <php.ini> using ini_set(). This function requires two string arguments. First one is the name of the setting to be modified and the second one is the new value to be assigned to it.

Given line of code will enable the display_error setting for the script if it’s disabled.

ini_set('display_errors', '1');

We need to put the above statement, at the top of the script so that, the setting remains enabled till the end. Also, the values set via ini_set() are applicable, only to the current script. Thereafter, PHP will start using the original values from php.ini.

Before changing any settings via ini_set(), it’s necessary to determine that PHP allows modifying it or not. We can only change the settings that get listed as ‘PHP_INI_USER’ or ‘PHP_INI_ALL’ in the ‘Changeable’ column of PHP manual [http://www.php.net/manual/en/ini.list.php].

Let’s see an example where we are modifying the SQL connection timeout using ini_set() function and later on verify the configured value by using ini_get() function.

echo ini_get('mysql.connect_timeout');  // OUTPUT 60

ini_set('mysql.connect_timeout',100);

echo "<br>";

echo ini_get('mysql.connect_timeout');  // output 100

Q-43. How to change the file permissions in PHP?

Answer.

Permissions in PHP are very similar to UNIX. Each file has following three types of permissions.

  • Read,
  • Write and
  • Execute.

PHP uses the <chmod()> function to change the permissions of a specific file. It returns TRUE on success and FALSE on failure.

Following is the Syntax.

chmod(file,mode)

- file 

Mandatory parameter. It indicates the name of the file to set the permissions.

- mode

Mandatory parameter. Specifies the new permissions. The mode parameter consists of four numbers.
  • File
    • Mandatory parameter. It indicates the name of the file to set the permissions.
  • Mode
    • Mandatory parameter. Specifies the new permissions. The mode parameter consists of four numbers.
      1. The first number is always zero.
      2. The second number specifies the permissions for the owner.
      3. The third number specifies the permissions for the owner’s user group.
      4. The fourth number specifies the permissions for everybody else.

Possible values are (add up the numbers to set multiple permissions)

  • 1 = execute permissions
  • 2 = write permissions
  • 4 = read permissions

For Example.

To set read and write permission for owner and read for everybody else, we use.

chmod("test.txt",0644);

Q-44. What is the use of urlencode() and urldecode() in PHP?

Answer.

The use of urlencode() is to encode a string before using it in a query part of a URL. It encodes the same way as posted data from a web page is encoded. It returns the encoded string.

Following is the Syntax.

urlencode (string $str )

It is a convenient way for passing variables to the next page.

The use of urldecode() function is to decode the encoded string. It decodes any %## encoding in the given string (inserted by urlencode.)

Following is the Syntax.

urldecode (string $str )

Q-45. Which PHP Extension helps to debug the code?

Answer.

The name of that Extension is Xdebug. It uses the DBGp debugging protocol for debugging. It is highly configurable and adaptable to a variety of situations.

Xdebug provides following details in the debug information.

  • Stack and function trace in the error messages.
  • Full parameter display for user defined functions.
  • Displays function name, file name and line indications where the error occurs.
  • Support for member functions.
  • Memory allocation
  • Protection for infinite recursions

Xdebug also provides.

  • Profiling information for PHP scripts.
  • Code coverage analysis.
  • Capabilities to debug your scripts interactively with a front-end debugger.
  • Xdebug is also available via PECL.

Summary – Latest PHP Interview Questions and Answers.

We are hopeful that above PHP interview questions would lead you to the door of success. In this post, we’ve tried to touch upon a combination of core PHP concepts, programming and object-oriented constructs and built-in functions. However, if there is anything which is not clear or not covered here, then do write us. We’ll try our best to answer your queries.

Also, we’ll continuously update this blog with more questions in future. If you like to appreciate our efforts, then do share this post across.

3 comments on “PHP Interview Questions and Answer to Refer for Quick Preparation”

  1. Excellent post. I was searching for different things completely,
    but stumbled on your blog. I am pleased I did. Many thanks
    for sharing
    useful information. Thank you and best of luck.

  2. Never knew this, thanks for letting me know.

Leave a Reply

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

  • twitter
  • facebook
  • instagram
  • linkedin