Top 115 PHP Interview Questions you must know

Last updated on August 27th, 2017 at 10:24 am

Here I have compiled a number of PHP Interview Questions. I have divided into several categories for better reading and understand

General PHP Interview Questions

Syntax PHP Interview Questions

Session and cookies PHP Interview Questions

mysql PHP Interview Questions

PHP Interview Questions

General PHP Interview Questions

1) What is PHP?

PHP is a web language based on scripts that allows developers to dynamically create generated web is an open source server side scripting language commonly used for web applications.Read below article for more information

PHP introduction and uses

Why I use PHP

how to write first php program

Can I view PHP files locally on my PC?

What is php

2) What does the initials of PHP stand for?

PHP means PHP: Hypertext Preprocessor.

3) Which programming language does PHP resemble to?

PHP syntax resembles Perl and C

4) What does PEAR stands for?

PEAR means “PHP Extension and Application Repository”. it extends PHP and provides a higher level of programming for web developers.

5) What is Open Source Software?

Software in which the source codes are freely used, modify, and shared by anyone are called Open Source Software. These can also be distributed under licenses that adhere with the Open Source Definition.

6) What is Zend Engine?

a)Zend Engine is used internally by PHP as a compiler and runtime engine. PHP Scripts are loaded into memory and compiled into Zend opcodes.
b)These opcodes are executed and the HTML generated is sent to the client.
c)The Zend Engine provides memory and resource management, and other standard services for the PHP language. Its performance, reliability and extensibility played a significant role in PHP’s increasing popularity.
d) We have different Zend engine version with different release of PHP


7) What is the main difference between PHP 4 and PHP 5?

PHP 5 presents many additional OOP (Object Oriented Programming) features.

PHP 4 uses Zend Engine 1 while PHP 5 uses Zend engine 2

8) What are some new features introduced in PHP7?

Lot of new features are introduced in PHP7. It is said to be quite faster then previous PHP version

a.Zend Engine 3 performance improvements and 64-bit integer support on Windows
b.uniform variable syntax AST-based compilation process
c.added Closure::call()
d.bitwise shift consistency across platforms
e.(null coalesce) operator
f.Unicode codepoint escape syntax
g.return type declarations
h.and scalar type (integer, float, string and boolean) declarations.

9) what is sql injection ?
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

10) What is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique which allows updating parts of a web page, without reloading the whole page. Data is exchanged asynchronously in small amounts of data with the server.

11) What is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library. It is an easy-to-use API which makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler across a multitude of browsers.

12) How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass informations from HTML to PHP.

How to Use HTML Inside PHP on the Same Page

Handling HTML forms with PHP

13) How can PHP and Javascript interact?

PHP and Javascript cannot directly interacts since PHP is a server side language and Javascript is a client side language. However we can exchange variables since PHP is able to generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

14) What is MySQL database?

it is a database system used on the web which runs on a server
it is very fast, reliable, and easy to use and ideal for both small and large applications
it uses standard ANSI SQL
it compiles on a number of platforms and is free to download and use
it is developed, distributed, and supported by Oracle Corporation
it is named after co-founder Monty Widenius’s daughter: My

Step by step guide to build local Apache PHP MySQL development environment on windows

15) What is CAPTCHA
CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart. To prevent spammers from using bots to automatically fill out forms, CAPTCHA programmers will generate an image containing distorted images of a string of numbers and letters. Computers cannot determine what the numbers and letters are from the image but humans have great pattern recognition abilities and will be able to fairly accurately determine the string of numbers and letters. By entering the numbers and letters from the image in the validation field, the application can be fairly assured that there is a human client using it.



 PHP syntax  Interview Questions

1) How do you execute a PHP script from the command line? What about if we need run the interactive PHP shell from the command line interface?

PHP command line interface (CLI) php script.php
interactive PHP shell from the command line interface php -a script.php

2) What are 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—- ] ?>


<? [— PHP code —] ?>

3) How can we display the output directly to the browser?

To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.

4) Is multiple inheritance supported in PHP?

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

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

‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.

6) What type of operation is needed when passing values through a form or an URL?

If we would like to pass values througn a form or an URL then we need to encode and to decode them using htmlspecialchars() and urlencode().

7) How can I display text with a PHP script?

Two methods are possible:

<!–?php echo “Method 1”; print “Method 2”; ?–>
<!–?php echo “Method 1”; print “Method 2”; ?–>

Php tutorial: Constant and echo-print statement

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

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

10) What should we do to be able to export data into an Excel file?

The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as separator between fields and then to open the file with Excel.

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

Useful strings function in PHP

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


Function and Variable PHP Interview Questions

1) What is needed to be able to use image function?

GD library is needed to be able execute image functions.

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

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

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

4) How failures in execution are handled with include() and require() functions?

If the function require() cannot access to the file then it ends with a fatal error. However, the include() function gives a warning and the PHP script continues to execute.

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

require() require() includes and evaluates a specific file
require_once() require_once() does that only if it has not been included before (on the same page).

So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don’t include the file more times and you will not get the “function re-declared” error.


6)What is the main difference between include() and require()?

require() produces a FATAL ERROR if file is not present
require_once() produces a warning only if file is not present


7) What is the main difference between include() and include_once()?

There is also include_once() which is the same as include(), but the difference between them is the same as the difference between require() and require_once().

include or require function in PHP with practical examples

8) How can we display information of a variable and readable by human with PHP?

To be able to display a human-readable result we use print_r().

9) What is the function file_get_contents() useful for?

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

10) How can we access the data sent through the URL with the GET method?

In order to access the data sent via the GET method, we you use $_GET array like this:

$variable = $_GET[“var”]; this will now contain ‘value’

11) How can we access the data sent through the URL with the POST method?

To access the data sent this way, you use the $_POST array.

Imagine you have a form field called ‘username’ on the form, when the user clicks submit to the post form, you can then access the value like this:


12) How can we check the value of a given variable is a number?

we can use the function  is_numeric() to check whether it is a number or not.

13) How can we check the value of a given variable is alphanumeric?

we can use the function  ctype_alnum to check whether it is an alphanumeric value or not.

14) How do I check if a given variable is empty?

we can it using  the empty() function.

15) What does the unlink() function means?

it is dedicated for file system handling. It simply deletes the file given as entry.

16) What does the unset() function means?

it is dedicated for variable management. It will make a variable undefined.

17) How do I escape data before storing it into the database?

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

18) How is it possible to remove escape characters from a string?

The stripslashes function enables us to remove the escape characters before apostrophes in a string.

Useful strings function in PHP

19) How can we automatically escape incoming data?

We have to enable the Magic quotes entry in the configuration file of PHP.

20) Is it possible to remove the HTML tags from data?

The strip_tags() function enables us to clean a string from the HTML tags.

21) 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:

function increment_num()
{ static $t1 = 1; echo $t1; $t1++; }
increment_num() ;
increment_num() ;
increment_num() ;

PHP tutorial: Variables in PHP

22) How can we define a variable accessible in functions of a PHP script?

This feature is possible using the global keyword.

23) How is it possible to return a value from a function?

A function returns a value using the instruction ‘return $value;’

PHP Functions with practical examples

24) What is the most convenient hashing method to be used to hash passwords?

It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. hence, hashing passwords with these algorithms can vulnerability.

25) Which cryptographic extension provide generation and verification of digital signatures?

The PHP-openssl extension provides several cryptographic operations including generation and verification of digital signatures.

26) How a constant is defined in a PHP script?

The define() directive lets us defining a constant as follows:

define (“DBNAME”, TECH);

Php tutorial: Constant and echo-print statement

27) How can you pass a variable by reference?

To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2

28) How is it possible to cast types in PHP?

The name of the output type have 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


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

30) How to Check if string contains specific words?

You can use the strpos function which is used to find the occurrence of one string inside other

31) What does accessing a class via :: means?

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

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

In PHP, objects passed by value.

33) Are Parent constructors called implicitly inside a class constructor?

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


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

35) What does $GLOBALS means?

it is a PHP super global variable array which is used to access global variables from anywhere in the PHP script . PHP stores all global variables in an array called $GLOBALS[index]. The index holds the name of the variable.

36) What does $_SERVER means?

it is a PHP super global variable array which holds information about headers, paths, and script locations

37) What does $_FILES means?

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


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

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

40) What does $_ENV means?

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

41) How to get ip address in php?

We can use the command $_SERVER[‘REMOTE_ADDR’]

42) How to convert array to json in php?
$array = array(‘tom’,’harry’);
echo json_encode($array); //use json_decode for decode

43) What is the use of “ksort” in php?

It is used for sort an array by key in reverse order.

php array functions

44) What does $_REQUEST means?

it is used to collect data after submitting an HTML form.

45) what is the use of isset() in php?
This function is used to determine if a variable is set and is not NULL

46) What are the encryption techniques in PHP?

MD5: PHP implements the MD5 hash algorithm using the md5 function.

eg : $encrypted_text = md5 ($msg);

mcrypt_encrypt: string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] );

Encrypts plaintext with given parameters

47) What is the use of the function htmlentities?

htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.


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


Sessions and Cookies PHP Interview Questions

1) what is the definition of a session?

A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

2) What’s the difference between a cookie and a session in PHP?

PHP sessions improve upon cookies because they allow web applications to store and retrieve more information than cookies. PHP sessions actually use cookies, but they add more functionality and security.

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser. Sessions use a session identifier to locate a particular user’s session data. This session identifier is normally stored in the user’s web browser in a cookie, but the sensitive data that needs to be more secure — like the user’s ID, name, etc. — will always stay on the server.


3) Can PHP sessions work without cookies?.
Sessions in PHP normally do use cookies to function. But, PHP sessions can also work without cookies in case cookies are disabled or rejected by the browser that the PHP server is trying to communicate with.

4) Where does the session stored, either client side or server side?

Session are stored in Server side. Session are secure.

PHP sessions, unlike cookies which are just stored on the user’s browser, need a temporary directory on the server where PHP can store the session data. For servers running Unix this isn’t a problem at all, because the /tmp directory is meant to be used for things like this.


5) How to initiate a session in PHP?

Sessions must use the session_start function

The use of the function session_start() lets us activates a session.

A very important thing to remember when using sessions is that each page that will use a session must begin by calling the session_start() function. The session_start() function tells PHP to either start a brand new session or access an existing one.

6) How session_start in PHP uses cookies

The first time the session_start() function is used, it will try to send a cookie with a name of PHPSESSID and a value of something that looks like e875785670baa8e10a44c878df89a2044b – which is the session identifier that contains 32 hexadecimal letters. Because cookies must be sent before any data is sent to the browser, this also means that session_start must be called before any data is sent to the Web browser.

7) how Registering values to the session works

After the session_start function is called, values can be registered to the session using the $_SESSION associative array.

8) How is it possible to propagate a session id?

It is possible to propagate a session id via cookies or URL parameters.

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

10) When sessions ends?

Sessions automatically ends when the PHP script finish executing, but can be manually ended using the session_write_close().

11) What is the difference between session_unregister() and session_unset()?

The session_unregister() function unregister a global variable from the current session and the session_unset() function free all session variables.

12) How to get the value of current session id?

session_id() function returns the session id for the current session.

13) What does $_COOKIE means?

it is an associative array of variables sent to the current PHP script using the HTTP Cookies.

14) How can we pass the variable through the navigation between the pages?

It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.

15) Is it possible to extend the execution time of a php script?

The use of the set_time_limit(int seconds) enables us to extend the execution time of a php script. The default limit is 30 seconds.

16) Is it possible to destroy a cookie?

Yes, it is possible by setting the cookie with a past expiration time.

17) What is the default session time in php?

The default session time in php is until closing of browser

Other PHP Interview Questions

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

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

3) what is the difference between for and foreach?

for is expressed as follows:

for (expr1; expr2; expr3)


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.


4) Is it possible to submit a form with a dedicated button?

It is possible to use the document.form.submit() function to submit the form. For example: <input type=button value=”SUBMIT” onClick=”document.form.submit()”>

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

6) Is it possible to protect special characters in a query string?

Yes, we use the urlencode() function to be able to protect special characters.

7) What are the three classes of errors that can occur in PHP?

The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors (critical errors).

8) When a conditional statement is ended with an endif?

When the original if was followed by : and then the code block without braces.

9) 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;

10) What is the best way to remove or turn off warning messages in PHP?

In order to remove a warning message in PHP all you have to do is use the error_reporting function in PHP.

11) How to use the error_reporting function to turn off warnings in PHP

// Turn off all error reporting

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings …)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting(E_ALL ^ E_NOTICE);

// Report all PHP errors (see changelog)

// Report all PHP errors

// Same as error_reporting(E_ALL);
ini_set(‘error_reporting’, E_ALL);

12) What is Another way to hide or remove warning messages in PHP

Another option to remove warning messages in PHP is to use what is called the error control operator – which is basically just the at sign – the “@”. When the “@” sign is put in front of an expression, any error message that might be generated by that expression will be ignored.

The “@” error control prefix operator will even disable error reporting for critical run time errors. For this reason, you should only use this operator if you really know what you are doing. The “@” can only be used in front of expressions – so it can not be used in front of a function or class definition, a for loop, etc. But, it can be used in front of a call to a function. Here is what it would look like in that scenario:

@someFunctionCall( );

Php with mysql Interview questions


1) How to create database connection and query in PHP?

a)The mysql is the historical API
b)The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
c) PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don’t use specific RDBM function in your queries), also object-oriented


2) How to connect mysqli with php using Object-Oriented Way?
$host = “localhost”;
$username = “root”;
$password = “”;
$conn = new mysqli($host, $username, $password);
//connect to server
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
echo “Connected successfully”;


3) How to connect mysqli with php using Procedural Way?
$host = “localhost”;
$username = “root”;
$password = “”;
$conn = mysqli_connect($host, $username, $password);
//connect to server
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
echo “Connected successfully”;


4) How to connect mysqli with php using PDO?
$host = “localhost”;
$username = “root”;
$password = “”;
$conn = new PDO(“mysql:host=$host;dbname=myDB”, $username, $password);
// set the PDO error mode to exception
echo “Connected successfully”;



5) what is difference between mysql_connect and mysql_pconnect?

PHP Interview Questions

6). What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

PHP Interview Questions

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

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

<!–?php $database = mysql_connect(“HOST”, “USER_NAME”, “PASSWORD”); mysql_select_db(“DATABASE_NAME”,$database); ?–>

8) How the result set of Mysql be handled in PHP?

The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row


using mysqli_fetch_array, mysqli_fetch_assoc, mysqli_fetch_object or mysqli_fetch_row


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

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

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

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

11) What is the difference between mysql_fetch_object() and mysql_fetch_array()?

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

Good Reference Material

PHP material

Learning PHP


Hope you like these PHP Interview Questions and answers. Please do provide feedback for this post.



Leave a Reply