Php Interview Questions

What is PHP?

PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very easy for learning.

What are the common usage of PHP?

Common uses of PHP −

  • PHP performs system functions, i.e. from files on a system it can create, open, read, write, and close them.
  • PHP can handle forms, i.e. gather data from files, save data to a file, thru email you can send data, return data to the user.
  • You add, delete, modify elements within your database thru PHP.
  • Access cookies variables and set cookies.
  • Using PHP, you can restrict users to access some pages of your website.
  • It can encrypt data.

In how many ways you can embed PHP code in an HTML page?

All PHP code must be included inside one of the three special markup tags ate are recognised by the PHP Parser.

<?php PHP code goes here ?> <? PHP code goes here ?> <script language=“php”> PHP code goes here </script> Most common tag is the <?php

What is the use of “echo” in php?

It is used to print a data in the webpage, Example: <?php echo ‘Car insurance’; ?> , The following code print the text in the webpage

How to include a file to a php page?

We can include a file using “include() ” or “require()” function with file path as its parameter.

require_once(), require(), include().What is difference between them?

require() includes and evaluates a specific file, while 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.

Differences between GET and POST methods ?

We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

What is the difference between Session and Cookie?

The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user’s computers in the text file format. Cookies can’t hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking

What is the use of explode() function ?

Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.

What is the importance of “method” attribute in a html form?

“method” attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

Define Object-Oriented Methodology

Object orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships

Difference between mysql_connect and mysql_pconnect?

There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that’s already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection… the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

What are the different types of errors in PHP ?

Here are three basic types of runtime errors in PHP:

  • Notices: These are trivial, non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all – although you can change this default behavior.
  • Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but 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 cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

What is PEAR?

PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.

Distinguish between urlencode and urldecode?

This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.

How can we increase the execution time of a PHP script?

  • Default time allowed for the PHP scripts to execute is 30 secs mentioned in the php.ini file. The function used is set_time_limit(int sec). If the value passed is ‘0’, it takes unlimited time. It should be noted that if the default timer is set to 30 sec, and 20 sec is specified in set_time_limit(), the script will run for 45 seconds.
  • This time can be increased by modifying the max_execution_time in secs. The time must be changed keeping the environment of the server. This is because modifying the execution time will affect all the sites hosted by the server.
  • The script execution time can be increased by

>Using sleep() function in PHP script

>Using set_time_limit() function

>The default limit is 30 seconds. The time limit can be set to zero to impose no time limit to pause.

What is the purpose of php.ini file?

The PHP configuration file, php.ini, is the final and most immediate way to affect PHP’s functionality. The php.ini file is read each time PHP is other words, whenever httpd is restarted for the module version or with each script execution for the CGI version. If your change isn.t showing up, remember to stop and restart httpd. If it still isn.t showing up, use phpinfo() to check the path to php.ini.

What do you mean by having PHP as whitespace insensitive?

Whitespace is the stuff you type that is typically invisible on the screen, including spaces, tabs, and carriage returns (end-of-line characters). PHP whitespace insensitive means that it almost never matters how many whitespace characters you have in a whitespace character is the same as many such characters.

What are the characteristics of PHP variables?

Here are the most important things to know about variables in PHP.

  • All variables in PHP are denoted with a leading dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with the = operator, with the variable on the left-hand side and the expression to be evaluated on the right.
  • Variables can, but do not need, to be declared before assignment.
  • Variables in PHP do not have intrinsic types – a variable does not know in advance whether it will be used to store a number or a string of characters.
  • Variables used before they are assigned have default values.
  • PHP does a good job of automatically converting types from one to another when necessary.
  • PHP variables are Perl-like.

What are the different types of PHP variables?

PHP has a total of eight data types which we use to construct our variables −

  • Integers − are whole numbers, without a decimal point, like 4195.
  • Doubles − are floating-point numbers, like 3.14159 or 49.1.
  • Booleans − have only two possible values either true or false.
  • NULL − is a special type that only has one value: NULL.
  • Strings − are sequences of characters, like ‘PHP supports string operations.’
  • Arrays − are named and indexed collections of other values.
  • Objects − are instances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class.
  • Resources − are special variables that hold references to resources external to PHP (such as database connections).

How will you define a constant in PHP?

To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.

What are the differences between PHP constants and variables?

  • There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
  • Constants cannot be defined by simple assignment, they may only be defined using the define() function.
  • Constants may be defined and accessed anywhere without regard to variable scoping rules.
  • Once the Constants have been set, may not be redefined or undefined.

What is the purpose of _CLASS_ constant?

_CLASS_ − The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased.

How will you redirect a page using PHP?

The PHP header() function supplies raw HTTP headers to the browser and can be used to redirect it to another location. The redirection script should be at the very top of the page to prevent any other part of the page from loading. The target is specified by the Location: header as the argument to the header() function. After calling this function the exit() function can be used to halt parsing of rest of the code.

How can we execute a PHP script using command line?

  • Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
  • Remember that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

How can we execute a PHP script using command line?

  • Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.
  • Remember that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

What is htaccess? Why do we use this and where?

  • htaccess files are configuration files of Apache Server that provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
  • These .htaccess files are used to change the functionality and features of Apache web server.
    For instance, htaccess file is used for url rewrite.
    –> It is used to make the site password protected.
    –> .htaccess file can restrict some ip addresses so that on restricted ip addresses, the site will not open.

What is the purpse $_REQUEST variable?

The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

How will you start a session in PHP?

A PHP session is easily started by making a call to the session_start() function.This function first checks if a session is already started and if none is started then it starts one. It is recommended to put the call to session_start() at the beginning of the page.

What is function overriding?

Function definitions in child classes override definitions with the same name in parent classes. In a child class, we can modify the definition of a function inherited from parent class.

What are interfaces in PHP?

Interfaces are defined to provide a common function names to the implementors. Different implementors can implement those interfaces according to their requirements. You can say, interfaces are skeltons which are implemented by developers.

What is the actually used PHP version?

Version 5 is the actually used version of PHP.

What does the initials of PHP stand for?

PHP means PHP: Hypertext Preprocessor.

Which programming language does PHP resemble to?

PHP syntax resembles Perl and C

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.

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:

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

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

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—- ] ?> and <? [—  PHP code  —] ?>

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

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

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

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

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.

How comparison of objects is done in PHP5?

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

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.

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

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.

What is needed to be able to use image function?

GD library is needed to be able execute image functions.

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

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

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.

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.

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:

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

What is the function file_get_contents() usefull for?

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

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:

What is the function mysql_pconnect() usefull for?

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

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.

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.

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

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

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.

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’

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 ‘var’ on the form, when the user clicks submit to the post form, you can then access the value like this:


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

It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.

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

It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.

How do I check if a given variable is empty?

If we want to check whether a variable has a value or not, it is possible to use the empty() function.

What does the unlink() function means?

The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.

What does the unset() function means?

The unset() function is dedicated for variable management. It will make a variable undefined.

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

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

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.

How can we automatically escape incoming data?

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

What does the function get_magic_quotes_gpc() means?

The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.

Is it possible to remove the HTML tags from data?

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

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:

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

This feature is possible using the global keyword.

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

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

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.

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.

How a constant is defined in a PHP script?

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

define (“ACONSTANT”, 123);

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

Will a comparison of an integer 12 and a string “13” work in PHP?

“13” and 12 can be compared in PHP since it casts everything to the integer type.

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

When a conditional statement is ended with an endif?

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

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 passed by value.

Are Parent constructors called implicitly inside a class constructor?

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


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;


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.

what is the definition of a session?

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

How to initiate a session in PHP?

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

How is it possible to propagate a session id?

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

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.

When sessions ends?

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

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.

What does $GLOBALS means?

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

What does $_SERVER means?

$_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.

Review Date
Reviewed Item
I got nice php interview questions and answers helpful to everyone, Thank you Iteanz, Keep Updating More.
Author Rating