Latest PHP Interview Questions to Refer for Quick Preparation

Here, we have the latest PHP interview questions for candidates who are actively looking for a job in PHP and determined to succeed. Our team has 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.

Latest PHP Interview Questions.

PHP Interview Questions and Answers.

Top PHP Interview Questions and Answers.

PHP Interview Questions & 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.

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.

 

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.

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

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.

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.

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.

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.

Here is an example.

Above code displays the following output.

 

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.

Let’s take an example.

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

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

 

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.

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.

 

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.

php interview questions - lifecycle of php session

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.

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

Let’s see the complete example.

 

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.

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

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).

 

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.

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

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

Syntax for <implode()> is as follows.

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.

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

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

It is equivalent to the following.

Syntax for explode() is as follows.

 

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.

 

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.

Let’s take an example to understand it better.

The <stristr()> function.

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

Syntax:

Let’s take an example to understand it better.

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

 

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.

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.

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.

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.

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.

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.

Here is the description for each of the parameters.

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

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

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.

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

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.

 

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.

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.

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

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

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

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

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

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

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.

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).

 

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.

Best,

TechBeamers.

Leave a Reply

*