PHP and Interview Questions

PHP Interview Questions and Answers

Posted in PHP, Interview Questions
PHP Interview Questions and Answers

Table of Contents

Hypertext Preprocessor also abbreviated as PHP is widely used scripting language specially used for web development and can be embedded into HTML and is mostly executed in the server. This open-source language was created in 1994 and is now managed by the PHP group. The language can run on various platforms such as Windows, Linux, MacOSX, and is compatible with most of the servers used today like Apache and IIS; the language also supports a wide range of databases. 

So if you aspire to be a PHP developer, we have made a collection of popular PHP interview questions to start your journey if you are a fresher or to contribute your journey if you are professional and want to upgrade your skills. 

Best PHP Interview Questions and Answers

Once you are done with double-checking all PHP core concepts and working hard to build adequacy for best PHP frameworks, it’s time to assess how good you are. To help you, here we have compiled a list of Most frequently asked PHP interview questions that will ensure you hit it right:

Question: Can you provide an example of a PHP Web Application Architecture?

Answer:PHP Web Application Architecture
Question: Define the use of .htaccess and php.ini files in PHP?

Answer: Both of them are used for making changes to the PHP settings.

  • .htaccess – A special file that can be used to change or manage the behavior of a website. Directing all users to one page and redirecting the domain’s page to https or www are two of the most important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache module.
  • php.ini – This special file allows making changes to the default PHP settings. Either the default php.ini file can be edited, or a new file can be created with relevant additions and then saved as the php.ini file. For php.ini to work, PHP needs to run as CGI.

Question: Draw a comparison between the compile-time exception and the runtime exception. What are they called?

Answer: Checked exception is the exception that occurs at the compile time. As it is not possible to ignore this type of exception, it needs to be handled cautiously. An unchecked exception, on the other side, is the one that occurs during the runtime. If a checked exception is not handled, it becomes an unchecked exception.

Question: Explain Path Traversal?

Answer: Path Traversal is a form of attack to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. To operate the web application file, Path Traversal makes use of the dot-dot-slash sequences.

The attacker can disclose the content of the file attacked using the Path Traversal outside the root directory of a web server or application. It is usually done to gain access token, secret passwords, and other sensitive information stored in the files.

Path Traversal is also known as Directory Traversal. It enables the attacker to exploit vulnerabilities present in the web file under attack.

Question: Explain the difference between GET and POST requests.

Answer: Any PHP developer needs to have an adequate understanding of the HTTP protocol. The differences between GET and POST are an indispensable part of the HTTP protocol learning. Here are the major differences between the two requests:

  • GET allows displaying the submitted data as part of the URL. This is not the case when using POST as during this time, the data is encoded in the request.
  • The maximum number of characters handled by GET is limited to 2048. No such restrictions are imposed on POST.
  • GET provides support for only ASCII data. POST, on the other hand, allows ASCII, binary data, as well as other forms of data.
  • Typically, GET is used for retrieving data while POST is used for inserting and updating data.

Question: Explain the mail function and its syntax.

Answer: To directly send emails from a script or website, the mail() function is used in PHP. It has a total of 5 arguments. The general syntax of a mail function is:

mail (to, subject, message, headers, parameters);
  • to denotes the receiver of the email
  • subject denotes the subject of the email
  • the message is the actual message that is to be sent in the mail (Each line is separated using /n, and the maximum character limit is 70.)
  • headers denote additional information about the mail, such as CC and BCC (Optional)
  • parameters denote to some additional parameter to be included in the send mail program (Optional)

Question: What is Memcache and Memcached in PHP? Is it possible to share a single instance of a Memcache between several PHP projects?

Answer: Memcached is an effective caching daemon designed specifically for decreasing database load in dynamic web applications. Memcache module offers a handy procedural and object-oriented interface to Memcached.

Memcache is a memory storage space, and it is possible to run Memcache on a single or several servers. Hence, it is possible to share a single instance of Memcache between multiple projects.

It is possible to configure a client to speak to a distinct set of instances. Therefore, running two different Memcache processes on the same host is also allowed. Despite running on the same host, both of such Memcache processes stay independent, unless there is a partition of data.

Question: How can you update Memcached when changes are made to PHP?

Answer: There are two ways of updating the Memcached when changes are made to the PHP code:

  1. Proactively Clearing the Cache – This means clearing the cache when an insert or update is made
  2. Resetting the Cache – Reset the values once the insert or update is made

Question: How is the comparison of objects done in PHP?

Answer: The operator ‘==’ is used for checking whether two objects are instanced using the same class and have the same attributes as well as equal values. To test whether two objects are referring to the same instance of the same class, the identity operator ‘===’ is used.

Question: How is typecasting achieved in PHP?

Answer: The name of the output type needs to be specified in parentheses before the variable that is to be cast. Some examples are:

  • (array) – casts to array
  • (bool), (boolean) – casts to Boolean
  • (double), (float), (real) – casts to float
  • (int), (integer) – casts to integer
  • (object) – casts to object
  • (string) – casts to string

Question: How would you connect to a MySQL database from a PHP script?

Answer: To connect to some MySQL database, the mysqli_connect() function is used. It is used in the following way:

<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD");
mysqli_select_db($database,"DATABASE_NAME"); ?-->

Question: What are constructors and destructors in PHP? Can you provide an example?

Answer: The constructors and destructors in PHP are a special type of functions, which are automatically called when a PHP class object is created and destroyed, respectively.

While a constructor is used to initialize the private variables of a class, a destructor frees the resourced created or used by the class.

Here is a code example demonstrating the concept of constructors and destructors:

<?php
class ConDeConExample {
 private $name;
 private $link;
 public function __construct($name) {
 $this->name = $name;
 } # Constructor
 public function setLink(Foo $link){
 $this->link = $link;
 }
 public function __destruct() {
 echo 'Destroying: ', $this->name, PHP_EOL;
 } # Destructor
}
?>

Question: What are some common error types in PHP?

Answer: PHP supports three types of errors:

  • Notices – Errors that are non-critical. These occur during the script execution. Accessing an undefined variable is an instance of a Notice.
  • Warnings – Errors that have a higher priority than Notices. Like with Notices, the execution of a script containing Warnings remains uninterrupted. An example of a Notice includes a file that doesn’t exist.
  • Fatal Error – A termination in the script execution results as soon as such an error is encountered. Accessing a property of a non-existing object yields a Fatal Error.

Question: What are the most important advantages of using PHP 7 over PHP 5?

Answer:

  • Support for 64-bit Integers – While PHP 7 comes with built-in support for native 64-bit integers and also for large files, PHP 5 doesn’t provide support for either of them.
  • Performance – PHP 7 performs far better than PHP 5. PHP 7 uses PHP-NG (NG stands for Next Generation), whereas PHP 5 relies on Zend II.
  • Return Type – One of the most important downsides of PHP 5 is that it doesn’t allow for defining the return type of a function. This limitation is eliminated by PHP 7, which allows a developer to define the type of value returned by any function in the code.
  • Error Handling – It is extremely difficult to manage fatal errors in PHP 5. PHP 7, on the opposite, comes with a new Exception Objects engine. It helps in managing several major critical errors, which are now replaced with exceptions.
  • Anonymous Class – To execute the class only once, for increasing the execution time, we have the anonymous class in PHP 7. It is not available in PHP 5.
  • Group Use Declaration – PHP 7 allows all the classes, constants, and functions to be imported from the same namespace to be grouped in a single-use statement. This is known as group use declaration. The feature is not available in PHP 5.
  • New Operators – Several new operators are introduced to PHP 7, including ‘<=>’ and ‘??’ The former is known as the three-way comparison operator, and the latter is called the null coalescing operator.

Question: What are the various ways of handling the result set of Mysql in PHP?

Answer: There are four ways of handling the result set of Mysql in PHP:

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_fetch_row

Question: What are the Traits in PHP?

Answer: The mechanism allows for the creation of reusable code in PHP-like languages where there is no support for multiple inheritances. A trait can’t be instantiated on its own.

Question: What is a session in PHP? Write a code example to demonstrate the removal of session data.

Answer: The simplest way to store data for individual users against a unique session ID is by using a PHP session. It is used for maintaining states on the server as well as sharing data across several pages. This needs to be done because HTTP is a stateless protocol.

Typically, session IDs are sent to the browser using session cookies. The ID is used for retrieving existing session data. If the session ID is not available on the server, then PHP creates a new session and then generates a new session ID.

Here is the program for demonstrating how session data is removed:

<?php 
session_start();
$_SESSION['user_info'] = ['user_id' =>1,
'first_name' =>
'Hacker', 'last_name' =>
'.io', 'status' =>
'active'];
if (isset($_SESSION['user_info']))
{
echo "logged In";
}
unset($_SESSION['user_info']['first_name']);
session_destroy(); // Removal of entire session data
?>

Question: What would you say is the best hashing method for passwords?

Answer: Rather than using the typical hashing algorithms, including md5, sha1, and sha256, it is preferable to use either crypt() or hash(). While crypt() provides native support for several hashing algorithms, hash(,) provides support for even more of them.

Question: Why is it not possible for JavaScript and PHP to interact directly? Do you know any workarounds?

Answer: No direct interaction is possible between JS and PHP because while the former is a client-side language, the latter is a server-side language. An indirect interaction between the two leading programming languages can happen using exchanging variables.

This exchange of variable is possible due to two reasons:

  1. PHP can generate JavaScript code meant to be executed by the browser
  2. It is achievable to pass a specific variable back to PHP via the URL. Because PHP always gets to be executed before JavaScript, the JS variables must be passed via a form or the URL. To pass the variables, GET and POST are used. Similarly, to retrieve the passed variable, $_GET and $_POST are used.

Question: Write code in PHP to calculate the total number of days between two dates?

Answer:

<?Php 
$date1 = ‘2019-01-11’; # Date 1
$date2 = ‘2019-01-09’; # Date 2
$days = (strtotime($date1)-strtotime($date2))/(60*60*24);
echo $days;
?>

Output:
1

Answer: PHP is a popular server-side scripting language used by developers to dynamically create webpages. Originally, PHP meant Personal Home Page. However, today it stands for the recursive acronym PHP: Hypertext Preprocessor.

As of now, there is a wide range of PHP frameworks available. Three of the most popular PHP frameworks are briefly explained as follows:

  • CodeIgniter – Simplistic and powerful, CodeIgniter is an incredibly lightweight PHP framework with a hassle-free installation process and minimalistic configuration requirements. The complete framework is a mere 2 MB and that too, including the documentation. As it comes with many prebuilt modules that help in developing strong, reusable components, CodeIgniter is ideal for developing dynamic websites. The popular PHP framework also offers a smooth working experience on both dedicated as well as shared hosting platforms.
  • Laravel – Although not as old as some of the other popular PHP frameworks, Laravel is perhaps the most popular PHP framework. Launched in 2011, the immense popularity enjoyed by the PHP framework can be credited to its ability to offer additional speed and security for handling complex web applications. Laravel also eases the development process by reducing the complexity of repetitive tasks, including authentication, routing, sessions, and queuing.
  • Symfony – Used by PHP developers ever since its release back in 2005, Symfony is a popular PHP framework that has stood the test of time. It has matured over its run of almost one-and-a-half decade. An extensive PHP framework, Symfony, is the sole PHP framework that follows the standard of PHP and web completely. Popular CMSs like Drupal, OroCRM, and PHPBB make use of various Symfony components.

If you are interested in learning Codeigniter, Laravel or Symfony, then Hackr has programming community-recommended best tutorials and courses:

Question: Will you draw a comparison between server-side and client-side programming languages?

Answer: Server-side programming languages are used for building programs that run on a server and generate the contents of a webpage. Examples of server-side programming languages include C++, Java, PHP, Python, and Ruby. A server-side programming language helps in:

  • Accessing and/or writing a file present on the server
  • Interacting with other servers
  • Processing user input
  • Querying and processing the database(s)
  • Structuring web applications

Contrary to the server-side programming languages, client-side programming languages help in developing programs that run on the client machine, typically browser, and involves displaying output and/or additional processing, such as reading and writing cookies.

CSS, HTML, JavaScript, and VBScript are popular client-side programming languages. A client-side programming language allows:

  • Developing interactive webpages
  • Interacting with temporary storage and/or local storage
  • Making data and/or other requests to the server
  • Offering an interface between the server and the end-user

Question: Please explain the differences between the echo and print statements in PHP?

Answer: There are two statements for getting output in PHP - echo and print. Following are the distinctions between the two:

  • Although used rarely, echo has the ability to take multiple parameters. The print statement, on the contrary, can accept only a single argument
  • Echo has no return value whereas, print has a return value of 1. Hence, the latter is the go-to option for using in expressions
  • Generally, the echo statement is preferred over the print statement as it is slightly faster

Question: How do static websites differ from dynamic websites?

Answer: There are two types of websites, static and dynamic. Differences between the two are enumerated as follows:

  • Advantage – The main advantage of a static website is flexibility, whereas the main advantage for a dynamic website comes in the form of a CMS
  • Changes/Modification – Changes are made to the content of a static website only when the file is updated and published i.e., sent to the webserver. Dynamic websites, on the other hand, contains “server-side” code that allows the server to generate unique content when the webpage is loaded
  • Content – The content remains the same every time the page is reloaded for a static website. Contrarily, the content belonging to a dynamic website is updated regularly
  • Response – Static websites send the same response for every request whereas dynamic websites might generate different HTML for different requests
  • Technologies Involved – Mere HTML is used for building static websites while dynamic websites are developed using several technologies, such as ASP.Net, JSP, Servlet, and PHP

Question: Please explain the use of the imagetypes() function?

Answer: The imagetypes() function gives the image format and types supported by the present version of the GD-PHP.

Question: Can you explain the difference between ‘passing the variable by value’ and ‘passing the variable by reference’ in PHP?

Answer: Passing the variable by value means that the value of the variable is directly passed to the called function. It then uses the value stored in the variable. Any changes made to the function doesn’t affect the source variable.

Passing the variable by reference means that the address of the variable where the value is stored is passed to the called function. It uses the value stored in the passed address. Any changes made to the function does affect the source variable.

Question: What do you understand by typecasting and type juggling?

Answer: When a variable’s data type is converted explicitly by the user, it is known as typecasting. The PHP programming language doesn’t support explicit type definition in variable declaration. Hence, the data type of the variable is determined by the context in which the variable is used.

For example, if a string value is assigned to a $var variable, then it automatically gets converted to a string. Likewise, if an integer value is assigned to $var, then it becomes an integer. This is called type juggling.

Question: Could you explain how to fetch data from a MySQL database using PHP?

Answer: To begin with, you need to first establish a connection with the MySQL database that you wish to use. For that, you can use the mysqli_connect() function.

Suppose that the database that you need to access is stored on a server named localhost and has the name instanceDB. Also, it has user_name as the username and pass_word as the password.

For establishing a connection to the instanceDB, you need to use the following PHP code:

<?php
$servername = “localhost”;
$username = “user_name”;
$password = “pass_word”;
$dbname = “instanceDB”;
$conn = new mysqli($servername, $username, $password, $dbname);
if (!$conn) { // For checking connection to the database
die(“Connection failed: ” . mysqli_connect_error());
}

Next, you need to use the SELECT statement to fetch data from one or more tables. The general syntax is:

SELECT column_name from table_name

Suppose, we have a single table called instancetable with column_1, column_2, and column_3 in the instanceDB, then to fetch data; we need to add the following PHP code:

$sql = “SELECT column_1, column_2, column_3 from instancetable”;
$result = $conn->query($sql);

Question: How will you display text with PHP Script?

Answer: Either the echo statement or the print statement can be used for displaying text with a PHP script. In usual scenarios, the former is preferred over the latter because it is slightly faster.

Answer: There are a plethora of PHP-based Content Management Systems in use today. Drupal, Joomla, and WordPress are the most popular among the bunch.

Question: Can you explain PHP parameterized functions?

Answer: Functions with parameters are known as PHP parameterized functions. It is possible to pass as many parameters as you’d like inside a function. Specified inside the parentheses after the function name, these all parameters act as variables inside the PHP parameterized function.

Question: Can you explain the difference between mysqli_connect() and mysqli_pconnect() functions?

Answer: Both mysqli_connect() and mysqli_pconnect() are functions used in PHP for connecting to a MySQL database. However, the latter ensures that a persistent connection is established with the database. It means that the connection doesn’t close at the end of a PHP script.

Question: Explain $_SESSION in PHP?

Answer: The $_SESSION[] is called an associative array in PHP. It is used for storing session variables that can be accessed during the entire lifetime of a session.

Question: Explain the difference between substr() and strstr() functions?

Answer: The substr() function returns a part of some string. It helps in splitting a string part-by-part in PHP. This function is typically available in all programming languages with almost the same syntax.

General syntax:

substr(string, start, length);

The strstr() function is used for searching a string within another string in PHP. Unlike the substr() function, strstr() is a case-sensitive function.

General syntax:

strstr(string, search, before_string);

Question: Explain the use of the $_REQUEST variable?

Answer: $_REQUEST is an associative array that, by default, contains the contents of the $_COOKIE, $_GET, $_POST superglobal variables.

Because the variables in the $_REQUEST array are provided to the PHP script via COOKIE, GET, and POST input mechanisms, it could be modified by the remote user. The variables and their order listed in the $_REQUEST array is defined in the PHP variables_order configuration directive.

Question: Please enumerate the major differences between for and foreach loop in PHP?

Answer: Following are the notable differences between for and for each loop:

  • The for-each loop is typically used for dynamic array
  • The for loop has a counter and hence requires extra memory. The for-each loop has no counter, and hence there is no requirement for additional memory
  • You need to determine the number of times the loop is to be executed when using the for a loop. However, you need not do so while using the for each loop

Question: Is it possible to submit a form with a dedicated button?

Answer: Yes, it is possible to submit a form with a dedicated button by using the document.form.submit() method. The code will be something like this:

<input type=button value=“SUBMIT” onClick=“document.form.submit()”>

Question: Please explain whether it is possible to extend a final defined class or not?

Answer: No, it isn’t possible to extend a final defined class. The final keyword prevents the class from extending. When used with a method, the final keyword prevents it from overriding.

Question: Will it be possible to extend the execution time of a PHP script? How?

Answer: Yes, it is possible to extend the execution time of a PHP script. We have the set_time_limit(int seconds) function for that. You need to specify the duration, in seconds, for which you wish to extend the execution time of a PHP script. The default time is 30 seconds.

Summary

That’s all for now! Here are some important PHP tutorials to go for, just in case. Keep your calm, and stay confident during the big day.

Though having a good understanding of the technical concepts is important, your presentation is also one that’s being reviewed.

We would recommend you a great course that will help you enhance your interview skills with the maximum questions set: PHP Interview Questions with Solutions part 1.

We also recommend a great book to prepare for the PHP Interview, which is, Modern PHP: Modern PHP: New Features and Good Practices 1st Edition.

So, all the very best for your PHP interview!

People are also reading:

Vijay Singh

Vijay Singh

My name is Vijay Singh Khatri, and I enjoy meeting new people and finding ways to help them have an uplifting experience. I have had a variety of customer service opportunities, through which I was able to have fewer returned products and increased repeat customers, when compared with co-workers. Currently working with hackr.io View all posts by the Author

Leave a comment

Your email will not be published
Cancel
Milen Georgiev
Milen Georgiev

Vijay Singh, JS has a server-side implementation - Node.js
Direct communication is possible using web sockets.
If you don't require it to be two-side, then a simple XMLHTTP or fetch is enough for communication.

Gordon Carter
Gordon Carter

How do I connect to localhost?

Luis Oliver
Luis Oliver

To connect to a local host from your server, enter http://localhost/. For accessing the server from some other computer on the same network as yours, type in http://192.168.Y.Y where Y.Y is the IP address of the server.

Josefina Cooper
Josefina Cooper

How do I test PHP locally?

Rosemary Gibbs
Rosemary Gibbs

Well, you shouldn’t test PHP locally without installing a server because it won’t take you close to the production environment, and your debugging will be severely affected. This all leads to the uncertainty of whether your code will work in the real world or not. Although, there are programs from which you can test PHP locally. You can use VirtualBox to test PHP locally.

Cathy Stevens
Cathy Stevens

Is PHP 5.6 secure?

Tommy Chapman
Tommy Chapman

Honestly, PHP 5.6 is not secure anymore. PHP developers have declared that they didn’t back the PHP 5.6 version, and no security updates and bug fixes will be rolling out from now onwards.

Angelica James
Angelica James

What is the difference between PHP 5.6 and 7?

Jasmine Cummings
Jasmine Cummings

PHP 7 is the new updated and stable version of PHP 5.6. And both the versions have some notable differences mentioned below:

For the same code, the performance will significantly vary. PHP 7 will have better performance and speed than PHP 5.6 because of its updated New Generation engine (PHP-NG). While the PHP 5.6 still runs on the old Zend engine.

Craig Clayton
Craig Clayton

Can Python replace PHP?

Tamara Williamson
Tamara Williamson

Python can and cannot replace PHP. It all depends upon your use of the language. Talking specifically about web development, PHP is programmed in such a way that the web development function is embedded in the program itself. On the other hand, for web development in Python, you will have to use frameworks such as Pyramid, Flask, and Tornado.

Robin Green
Robin Green

What are the benefits of using PHP?

Lawrence Andrews
Lawrence Andrews

There are numerous benefits of using PHP for web development, as PHP is/has:
open-source
extendible
platform-independent
low maintenance cost
reliable
low development.

Tim
Tim

What question about compile time exceptions does here, PHP doesn't compile and don't have such exceptions. Further you bland checked/unchecked exceptions with compile time/runtime exceptions. It's completely different things.

Ross
Ross

"Why is it not possible for JavaScript and PHP to interact directly"

It's actually possible. You can pass PHP variables to JS but not backwards.

Milen Georgiev
Milen Georgiev

You can have two-way communication using web sockets.

Miley Cyrus
Miley Cyrus

Thanks for sharing this information.