Welcome to PHP Interview Questions with answers and detailed explanations. These questions will help you in your preparation for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

What is PHP?

PHP is an acronym for “PHP: Hypertext Preprocessor” · PHP is a widely-used, open-source scripting language · PHP scripts are executed on the server. PHP allows writing dynamically generated web pages efficiently and quickly. The syntax is mostly borrowed from C, Java and Perl. PHP is free to download and use.

PHP interview questions for freshers

Who is known as the father of PHP?

Rasmus Lerdorf

What was the old name of PHP?

The old name of PHP was Personal Home Page.

What is the name of scripting engine in PHP?

The scripting engine that powers PHP is called Zend Engine 2.

 How do you execute a PHP script from the command line?

Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as follows:

php script.php

How to run the interactive PHP shell from the command line interface?

Just use the PHP CLI program with the option -a as follows:

php -a

What is the correct and the most two common way to start and finish a PHP block of code?

The two most common ways to start and finish a PHP script are:

<?php [   ---  PHP code---- ] ?> 

and 

<? [---  PHP code  ---] ?>

Is multiple inheritance supported in PHP?

PHP supports only single inheritance; it means that a class can be extended from only one single class using the keyword ‘extended’.

How is the comparison of objects done in PHP?

We use the operator ‘==’ to test is two objects are instanced from the same class and have same attributes and equal values. We can test if two objects are referring to the same instance of the same class by the use of the identity operator ‘===’.

What is needed to be able to use image function?

GD library is needed to execute image functions.

What are the functions to be used to get the image’s properties (size, width, and height)?

The functions are getimagesize() for size, imagesx() for width and imagesy() for height.

What is the main difference between require() and require_once()?

require(), and require_once() perform the same task except that the second function checks if the PHP script is already included or not before executing it.

(same for include_once() and include())

How can I display text with a PHP script?

Two methods are possible:

<?php 
  echo "Method 1"; 
  print "Method 2"; 
?>

How is it possible to set an infinite execution time for PHP script?

The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded.’ It is also possible to specify this in the php.ini file.

What does the PHP error ‘Parse error in PHP – unexpected T_variable at line x’ means?

This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.

What is the function file_get_contents() useful for?

file_get_contents() lets reading a file and storing it in a string variable.

What are the popular Content Management Systems (CMS) in PHP?

  • WordPress: WordPress is a free and open-source content management system (CMS) based on PHP & MySQL. It includes a plug-in architecture and template system. It is mostly connected with blogging but supports another kind of web content, containing more traditional mailing lists and forums, media displays, and online stores.
  • Joomla: Joomla is a free and open-source content management system (CMS) for distributing web content, created by Open Source Matters, Inc. It is based on a model-view-controller web application framework that can be used independently of the CMS.
  • Magento: Magento is an open source E-trade programming, made by Varien Inc., which is valuable for online business. It has a flexible measured design and is versatile with many control alternatives that are useful for clients. Magento utilizes E-trade stage which offers organization extreme E-business arrangements and extensive support network.
  • Drupal: Drupal is a CMS platform developed in PHP and distributed under the GNU (General Public License).

What are the popular frameworks in PHP?

  • Laravel
  • CakePHP
  • CodeIgniter
  • Yii 2
  • Symfony
  • Zend Framework etc.

List some of the features of PHP7

  • Scalar type declarations
  • Return type declarations
  • Null coalescing operator (??)
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Closure::call method
  • Group use declaration
  • Generator return expressions
  • Generator delegation
  • Space ship operator

How a variable is declared in PHP?

A PHP variable is the name of the memory location that holds data. It is temporary storage.

$variableName=value;  

What are the different loops in PHP?

For, while do-while and foreach.

Differentiate between variables and constants in PHP

Few differences between variables and constants in PHP are given below:

VariablesConstants
The value of a variable can be changed during the execution.The constant value can’t be changed during script execution.
Variables require compulsory usage of the $ sign at the start.No dollar sign ($) is required before using a constant.
It is possible to define a variable by simple assignment.Constants can’t be defined by simple assignments. They are defined using the define() function.
The default scope is the current access scope.Constants can be accessed throughout without any scoping rules.

What is a session in PHP?

A session in PHP is a way to store information to be used across multiple pages of an entire website. The information is not stored on the user’s computer, unlike cookies. In a temporary directory on the server, a file will be created by the session where registered session variables and their values are stored. This information will be available to all pages on the site during that visit.

By default, session variables will last until the user closes the browser.

So Session variables hold single user information and are available to all pages in one application.

What is the method to register a variable into a session?

<?php  
Session_register($ur_session_var);  
?>

What is $_SESSION in PHP?

A session creates a file in a temporary directory on the server where registered session variables and their session id are stored. This data will be available to all pages on the site amid that visit.

The area of the temporary record is controlled by a setting in the php.ini document called session.save_path.

At the point when a session is begun following things happen –

  1. PHP first makes two duplicates of one of a kind session id for that particular session of the client which is an arbitrary string of 32 hexadecimal numbers, for example, 3c7foj34c3jjhkyepop2fc937e3443.
  2. One copy of unique session id automatically sent to the user?s computer for the sake of synchronization in future ahead, and one copy is being maintained at server side till the session is running.
  3. Whenever you want to access the page of website or web app, then session id of the current user will be associated with the HTTP header, and that will be compared by the session id which is being maintained at the server. After completing the comparison process, you can easily access the page of the website or web app
  4. A session ends when the user closes the browser, or after leaving the site, the server will terminate the session after a predetermined period, commonly 30 minutes duration.

What is PHP session_start() and session_destroy() function?

PHP session_start() function is used to start the session. It starts new or resumes the current session. It returns the current session if the session is created already. If the session is not available, it creates and returns new sessions.

Write syntax to open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.

Syntax:

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

How to read a file in PHP?

PHP provides various functions to read data from the file. Different functions allow you to read all file data, read data line by line, and read data character by character.

PHP file read functions are given below:

  • fread()
  • fgets()
  • fgetc()

How to write in a file in PHP?

PHP fwrite() and fputs() functions are used to write data into file. To write data into a file, you need to use w, r+, w+, x, x+, c or c+ mode.

How to delete file in PHP?

The unlink() function is used to delete a file in PHP.

bool unlink (string $filename)      

How can you send email in PHP?

The mail() function is used to send email in PHP.

bool mail($to,$subject,$message,$header);    

How can we increase execution time of a PHP script?

By default, the maximum execution time for PHP scripts is set to 30 seconds. If a script takes more than 30 seconds, PHP stops the script and returns an error.

You can change the script run time by changing the max_execution_time directive in the php.ini file.

When a script is called, set_time_limit function restarts the timeout counter from zero. It means, if default timer is set to 30 sec, and 20 sec is specified in function set_time_limit(), then script will run for 45 seconds. If 0sec is specified in this function, script takes unlimited time.

How to stop the execution of PHP script?

The exit() function is used to stop the execution of PHP script.

Explain PHP split() function.

The PHP split() function splits string into an array by regular expression.

How can we get IP address of a client in PHP?

$_SERVER["REMOTE_ADDR"];  

What is the meaning of a Persistent Cookie?

A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.

What is the use of the function ‘imagetypes()’?

imagetypes() gives the image format and types supported by the current version of GD-PHP.

What does PEAR stands for?

PEAR stands for “PHP Extension and Application Repository”. PEAR is a framework and repository for all of the reusable PHP components.

PEAR provides a higher level of programming for web developers. It contains all kinds of PHP code snippets and libraries. It also provides you with a command-line interface to automatically install packages.

Is PHP a case-sensitive language?

PHP can be considered as a partial case-sensitive language. The variable names are completely case-sensitive but function names are not. Also, user-defined functions are not case-sensitive but the rest of the language is case-sensitive.

For example, user-defined functions in PHP can be defined in lowercase but later referred to in uppercase, and it would still function normally.

What are the different types of variables present in PHP?

There are 8 primary data types in PHP which are used to construct the variables. They are:

  • Integers: Integers are whole numbers without a floating-point. Ex: 1253.
  • Doubles: Doubles are floating-point numbers. Ex: 7.876
  • Booleans: It represents two logical states- true or false.
  • NULL: NULL is a special type that only has one value, NULL. When no value is assigned to a variable, it can be assigned with NULL.
  • Arrays: Array is a named and ordered collection of similar type of data. Ex: $colors = array(“red”, “yellow”, “blue”);
  • Strings: Strings are a sequence of characters. Ex: “Hello InterviewBit!”
  • Resources: Resources are special variables that consist of references to resources external to PHP(such as database connections).
  • Objects: An instance of classes containing data and functions. Ex: $mango = new Fruit();

What is the difference between “echo” and “print” in PHP?

The main difference between echo and print in PHP are given below:

echoprint
echo can output one or more strings.print can only output one string and it always returns 1.
echo is faster than print because it does not return any value.print is slower compared to echo.
If you want to pass more than one parameter to echo, a parenthesis should be used.Use of parenthesis is not required with the argument list.

What is the difference between $message and $$message?

$message stores variable data while $$message is used to store variable of variables.

$message stores fixed data whereas the data stored in $$message may be changed dynamically.

Tell me some of the disadvantages of PHP

The cons of PHP are:

  • PHP is not suitable for giant content-based web applications.
  • Since it is open-source, it is not secure. Because ASCII text files are easily available.
  • Change or modification in the core behavior of online applications is not allowed by PHP.
  • If we use more features of the PHP framework and tools, it will cause poor performance of online applications.
  • PHP features a poor quality of handling errors. PHP lacks debugging tools, which are needed to look for warnings and errors. It has only a few debugging tools in comparison to other programming languages.

How can PHP and HTML interact?

PHP scripts have the ability to generate HTML, and it is possible to pass information from HTML to PHP.

PHP is a server-side language whereas HTML is a client-side language. So PHP executes on the server-side and gets its results as strings, objects, arrays, and then we use them to display its values in HTML.

This interaction helps bridge the gaps and use the best of both languages.

What are the ways to define a constant in PHP?

PHP constants are name or identifier that can’t be changed during execution of the script. PHP constants are defined in two ways:

  • Using define() function
  • Using const() function

What are magic constants in PHP?

PHP magic constants are predefined constants, which change based on their use. They start with a double underscore (__) and end with a double underscore (__).

What is the use of count() function in PHP?

The PHP count() function is used to count total elements in the array, or something an object.

What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this function.

What does isset() function?

The isset() function checks if the variable is defined and not null.

What are the methods to submit form in PHP?

There are two methods GET and POST.

What are the ways to include file in PHP?

PHP allows you to include file so that page content can be reused again. There are two ways to add the file in PHP.

  1. include
  2. require

What is the purpose of @ in PHP?

In PHP, @ is used for suppressing error messages. If any runtime error occurs on the line which consists @ symbol at the beginning, then the error will be handled by PHP.

Explain the importance of Parser in PHP?

A PHP parser is a software that converts source code into the code that computer can understand. This means whatever set of instructions we give in the form of PHP code is converted into a machine-readable format by the parser.

You can parse PHP code with PHP using the token_get_all() function.

What are the different types of Array in PHP?

There are 3 main types of arrays that are used in PHP:

  • Indexed Array: An array with a numeric key is known as the indexed array. Values are stored and accessed in linear order.
  • Associative Array: An array with strings for indexing elements is known as the associative array. Element values are stored in association with key values rather than in strict linear index order.
  • Multidimensional Array: An array containing one or more arrays within itself is known as a multidimensional array. The values are accessed using multiple indices.

Explain the main types of errors.

The 3 main types of errors in PHP are:

  • Notices: Notices are non-critical errors that can occur during the execution of the script. These are not visible to users. Example: Accessing an undefined variable.
  • Warnings: These are more critical than notices. Warnings don’t interrupt the script execution. By default, these are visible to the user. Example: include() a file that doesn’t exist.
  • Fatal: This is the most critical error type which, when occurs, immediately terminates the execution of the script. Example: Accessing a property of a non-existent object or require() a non-existent file.

What are traits?

Traits are a mechanism that lets you create reusable code in PHP and similar languages where multiple inheritances are not supported. It’s not possible to instantiate it on its own.

A trait is intended to reduce the limitations of single inheritance by enabling a developer to reuse sets of methods freely in many independent classes living in different hierarchies of class.

How does the ‘foreach’ loop work in PHP?

The foreach statement is a looping construct that is used in PHP to iterate and loop through the array data type.

This process is repeatedly done until the end of the array has been reached.

The syntax for using the foreach statement in PHP is given below:

foreach($array as $value)
{
   Code inside the loop;
}

What is the most used method for hashing passwords in PHP?

The crypt() function is used for this functionality as it provides a large number of hashing algorithms that can be used. These algorithms include sha1, sha256, or md5 which are designed to be very fast and efficient.

What is the difference between the include() and require() functions?

include() function

This function is used to copy all the contents of a file called within the function, text wise into a file from which it is called.

When the file is included cannot be found, it will only produce a warning (E_WARNING) and the script will continue the execution.

require() function:

The require() function performs same as the include() function. It also takes the file that is required and copies the whole code into the file from where the require() function is called.

When the file is included cannot be found, it will produce a fatal error (E_COMPILE_ERROR) and terminates the script.

What are cookies? How to create cookies in PHP?

A cookie is a small record that the server installs on the client’s computer. They store data about a user on the browser. Each time a similar PC asks for a page with a program, it will send the cookie as well.

By default, cookies are URL particular. For example, Gmail cookies are not supported by Yahoo and vice versa. Cookies are temporary and transitory by default. Per site 20 cookies can be created in a single website or web app. 50 bytes is the initial size of the cookie and 4096 bytes is the maximum size of the cookie.

In PHP, we can create cookies using the setcookie() function:

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

Here name is mandatory and the remaining parameters are optional.

Example:
setcookie(“instrument_selected”, “guitar”)

What is the meaning of ‘escaping to PHP’?

Escaping a string means reducing ambiguity in quotes used in that string.

For example, when you’re defining a string, you surround it in either double quotes or single quotes:
“Hello, InterviewBit.” 

But what if I include double quotes within the string?
“Hello “InterviewBit.”” 

Now I have ambiguity – the interpreter doesn’t know where does my string end. If I want to keep my double quotes, I have various options. I could use single quotes around my string:
‘Hello “InterviewBit.”‘ 

Or I can escape my quotes:
“Hello \”InterviewBit.\”” 

Any quote that is preceded by a slash is escaped and understood to be part of the value of the string.

Explain Path Traversal

Path traversal makes use of this symbol to operate the web application file. The attacker can reveal 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 to secret passwords, tokens, and other sensitive information stored in the files.

Path Traversal is also called “Directory Traversal”. It allows the attacker to exploit vulnerabilities present in the web file under attack.

Let’s take a simple example. Consider we have a “Show File” button that opens up some URL.

This technique is also called a dot-dot-slash attack, because it usually uses the special characters ../ (or \.. on Windows) to climb to a higher-level directory.

What is the meaning of a final method and a final class?

The final keyword in a declaration of the method indicates that the method cannot be overridden by subclasses. A class that is declared as final cannot be subclassed.

This is especially useful when we are creating an immutable class like the String class. Only classes and methods may be declared final, properties cannot be declared as final

How is it possible to cast types in PHP?

The name of the output type has to be specified in parentheses before the variable which is to be cast as follows:

* (int), (integer) – cast to integer

* (bool), (boolean) – cast to boolean

* (float), (double), (real) – cast to float

* (string) – cast to string

* (array) – cast to array

* (object) – cast to object

What does $GLOBALS mean?

$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.

What does $_SERVER mean?

$_SERVER is an array including information created by the web server such as paths, headers, and script locations.

What does $_FILES means?

$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.

What is the difference between $_FILES[‘userfile’][‘name’] and $_FILES[‘userfile’][‘tmp_name’]?

$_FILES[‘userfile’][‘name’] represents the original name of the file on the client machine,

$_FILES[‘userfile’][‘tmp_name’] represents the temporary filename of the file stored on the server.

How can we get the error when there is a problem to upload a file?

$_FILES[‘userfile’][‘error’] contains the error code associated with the uploaded file.

How can we change the maximum size of the files to be uploaded?

We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.

What does $_ENV mean?

$_ENV is an associative array of variables sent to the current PHP script via the environment method.

What does $_COOKIE mean?

$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies

What are the two main string operators?

The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is (‘.=’), which appends the argument on the right to the argument on the left.

What does the array operator ‘===’ means?

$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

What is the differences between $a != $b and $a !== $b?

!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).

How can we determine whether a PHP variable is an instantiated object of a certain class?

To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.

What is the goto statement useful for?

The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.

what is the difference between Exception::getMessage and Exception:: getLine?

Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.

What does the expression Exception::__toString means?

Exception::__toString gives the String representation of the exception.

How is it possible to parse a configuration file?

The function parse_ini_file() enables us to load in the ini file specified in filename and returns the settings in it in an associative array.

 How can we determine whether a variable is set?

The boolean function isset determines if a variable is set and is not NULL.

What is the difference between the functions strstr() and stristr()?

The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-sensitive. stristr() is identical to strstr() except that it is case insensitive.

hat is the difference between for and foreach?

for is expressed as follows:

for (expr1; expr2; expr3)

statement

The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues, and the statements inside for are executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.

However, foreach provides an easy way to iterate over arrays, and it is only used with arrays and objects.

What is the difference between ereg_replace() and eregi_replace()?

The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.

PHP Interview Questions For Experienced

What is the difference between characters \034 and \x34?

\034 is octal 34 and \x34 is hex 34.

what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?

$a and $b: TRUE if both $a and $b are TRUE.

$a & $b: Bits that are set in both $a and $b are set.

How is the ternary conditional operator used in PHP?

It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:

Expression_1 ? Expression_2 : Expression_3;

What is the function func_num_args() used for?

The function func_num_args() is used to give the number of parameters passed into a function.

 If the variable $var1 is set to 10 and the $var2 is set to the character var1, what’s the value of $$var2?

$$var2 contains the value 10.

What does accessing a class via :: means?

:: is used to access static methods that do not require object initialization.

In PHP, objects are they passed by value or by reference?

In PHP, objects are passed by reference.

Are Parent constructors called implicitly inside a class constructor?

No, a parent constructor have to be called explicitly as follows:

parent::constructor($value)

What’s the difference between __sleep and __wakeup?

__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.

What is faster?

1- Combining two variables as follows:

$variable1 = 'Hello ';

$variable2 = 'World';

$variable3 = $variable1.$variable2;

Or

2- $variable3 = "$variable1$variable2";

$variable3 will contain “Hello World”. The first code is faster than the second code especially for large large sets of data.

PHP & MySQL Interview Questions

How can we connect to a MySQL database from a PHP script?

To be able to connect to a MySQL database, we must use mysqli_connect() function as follows:

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

 What is the function mysql_pconnect() useful for?

mysql_pconnect() ensure a persistent connection to the database, it means that the connection does not close when the PHP script ends.

This function is not supported in PHP 7.0 and above

How be the result set of Mysql handled in PHP?

The result set can be handled using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row.

How is it possible to know the number of rows returned in the result set?

The function mysqli_num_rows() returns the number of rows in a result set.

Which function gives us the number of affected entries by a query?

mysqli_affected_rows() return the number of entries affected by an SQL query.

What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?

The mysqli_fetch_object() function collects the first single matching record where mysqli_fetch_array() collects all matching records from the table in an array.

How do I escape data before storing it in the database?

The addslashes function enables us to escape data before storage into the database.

what is the static variable in function useful for?

A static variable is defined within a function only the first time, and its value can be modified during function calls as follows:

<!--?php 

function testFunction() { 
   static $testVariable = 1; 
   echo $testVariable; $testVariable++; 
} 

testFunction();        //1 
testFunction();        //2 
testFunction();        //3 

?-->

Explain how you can update Memcached when you make changes to PHP?

When PHP changes you can update Memcached by

  • Clearing the Cache proactively: Clearing the cache when an insert or update is made
  • Resetting the Cache: It is similar to the first method but rather than just deleting the keys and waiting for the next request for the data to refresh the cache, reset the values after the insert or update.

Free PDF Download: PHP Interview Questions & Answers

Download PDF: PHP Interview Questions & Answers