PHP interview questions and answers

16 Apr

In this article we are providing you some PHP interview questions and answers that is frequently asked by interviewer. These question will help you to win interview question as well as you can understand basic concept of php language. We hope you find these questions useful. If you are an interviewer, Take the time to read the common PHP interview questions and answers you will most likely be asked.

What is PHP?

Php is a high level programming language mostly used to develop websites but php can also be used for general purpose. Php stands for the recursive acronym PHP Hypertext Preprocessor

What is the use of “echo” in php?

echo is used to get output of a php program on the screen it prints the value of expression or a variable.

How to include a file to a php page?

There are two ways to include files in php by include or require function. We can pass file path in this function to include file.

What’s the difference between include and require?

require means required if you will use require to include a file and if file is not found then it will throw fatal error and halt the execution and if you use include then a warning will be issued but execution will continue.

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

Generally we write common function in a separate common file and we include this file in our every php script. For this type of file we should use require_once it checks if file has been included then it will not include it again. If given file does not exists then it will throw fatal error.

instead of require_once() if one use require() then it will include file as many times as required() statement will be exists in the code.

Some time we need to use same block of code many times in a php program so we can use include statement.

Differences between GET and POST methods ?

As its name GET can be used to get the data from web server and POST can be used to post the form data to server. We can send 1024 bytes using GET method if we want to transfer large amount of data the we should use POST method.

How to declare an array in php?

Eg : var $arr = array('apple', 'grape', 'lemon');

What is the use of ‘print’ in php?

Print is used to output data to the screen. print has a return value of 1 so it can be used in expression. print can take only one parameter.

Example print(‘PHP Interview questions’);
print ‘Job Interview ‘);

What is use of in_array() function in php ?

in_array is applied on a array when you want to check if a value is exists in an array or not.
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";

What is use of count() function in php ?

count() returns length of an array or object.

What’s the difference between include and require?

You can understand by its name require mean must have. If you use require and file does not exists then it will throw fatal error and it will stop the execution of script.
In place of include() function does not stop execution of script it just issue a warning message.

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

How to set cookies in PHP?

Setcookie(“sample”, “ram”, time()+3600);

How to Retrieve a Cookie Value?

eg : echo $_COOKIE[“user”];

How to create a session? How to set a value in session ? How to Remove data from a session?

You can create session by session_start();

you can set value into session : $_SESSION[‘USER_ID’]=1;
Remove data from a session : unset($_SESSION[‘USER_ID’];8i

What types of loops exist in php?

for, while, do while and foreach (NB: You should learn its usage)

How to create a Mysql connection?


How to select a database?


How to execute an sql query? How to fetch its result ?

$query = mysql_query("SELECT * FROM `users` WHERE `user_id`='1'; ");
$result = mysql_fetch_array($query);
echo $result['fullname'];

Write a program using while loop
$c = 0;

while($c < 11) {
$c = $c + 1;
print $c;

How we can retrieve the data in the result set of MySQL using PHP?

1. mysql_fetch_row
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc

what does it mean by a function being binary-safe ?

Binary-safe mean you can pass any arbitrary data in this function and it returns always correct output. Binay unsafe function does not works correctly when you pass data with non ASCII characters
This is relevant because PHP does not cleanly separate string and binary data.

What is safe mode in php

Enabling Safe Mode imposes several restrictions on PHP scripts. These restrictions are mostly concerned with file access, access to environment variables and controlling the execution of external processes.

What is the use of explode() function ?

Syntax : array explode ( string $delimiter , string $string [, int $limit ] );
explode function split string into array. explode does not use regular expression.
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 difference between explode() and split() functions?

Split function splits string into array by regular expression. Explode splits a string into array by string.

What is the use of mysql_real_escape_string() function?

This function escape the special characters according to the character set of current connection. before using function mysql_query one should use this function and If binary data is to be inserted then this function must be used.

Write down the code for save an uploaded file in php.

if ($_FILES["file"]["error"] == 0)
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

How to create a text file in php?

$filename = "/home/user/myfile.txt";
$file = fopen( $filename, "w" );
if( $file == false ) {
echo ( "Error in opening new file" ); exit();
fwrite( $file, "This is a simple test\n" );
fclose( $file );

How to strip white space (or other characters) from the beginning and end of a string ?

trim function is used to remove white spaces and other defined characters from beginning and end of a string.
one define

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

The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.

How to redirect a page in php?

The following code can be used for it, header("Location:index.php");

How stop the execution of a php script ?

on can use exit or die function to stop execution of a php script.

How to set a page as a home page in a php based site ?

web server look for a file when we does provide file name in the url. web server tries to find index.htm, index.html or index.php. so if we put a file named index.php it will exeucte as a home page of website.

How to find the length of a string?

strlen() function used to find the length of a string

what is the use of rand() in php?

rand() function is used to generate random between two numbers. if you do not provide minimum and maximum number then it will return pseudo-random integer between 0 and getrandmax().

what is the use of isset() in php?

isset() function is used to check whether variable is exists or not. It is very useful when submitting form data. Before processing every $_GET OR $_POST variable we must check is it available or not to avoid undefined variable warning..

if(isset($_POST['name'])) {
$name = $_POST['name'];

What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?

Mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array() fetches an associative array, a numeric array, or both

What is mean by an associative array?

Associative arrays are arrays that use string keys is called associative arrays.

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

It is used in html form it can contain two values GET or POST. when we use GET all parameter of form will append in the url so you see what is being sent to server and GET is used when we need to send limited data to sever and the POST is used to send large amount of data to server and use can not see what data is being sent to server.

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

The action attribute is used to send form data to server. In this attribute the name of php file is assigned where form data need to be send.

What is the use of “enctype” attribute in a html form?

The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as “multipart/form-data” when we are using a form for uploading files

How to create an array of a group of items inside an HTML form ?

We can create input fields with same name for “name” attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP.

For instance :
<input name="MyArray[]" type="text" /> <input name="MyArray[]" type="text" /> <input name="MyArray[]" type="text" /> <input name="MyArray[]" type="text" />

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 entity. An object oriented model is a collection of objects and its inter-relationships

How do you define a constant?

constant is defined by define directive.
like define (“MYCONSTANT”,150)

How send email using php?

Using mail() function an email can be send through a php script. It accepts 5 parameters where 3 are required and 2 are optional parameters.

mail( to, subject, message, headers, parameters );

How to find current date and time?

The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional – if you don’t, the current timestamp will be used.

Difference between mysql_connect and mysql_pconnect?

mysql_connect is used to make connection to a mysql server. mysql_connect provide a new connection of a database and it will be close automatically when script goes end.
While mysql_pconnect creates persistent connection to a mysql server. It remains active after script execution end. mysql_pconnect() try to find a previously opened connection if one found then it returns that connection else it creates new persistent 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 is the use of “ksort” in php?

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

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

They are both variables. But $var is a variable with a fixed name. $$var is a variable who’s name is stored in $var. For example, if $var contains “message”, $$var is the same as $message.

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

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.

How to delete a file from the system

Unlink() deletes the given file from the file system.

How to get the value of current session id?

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

What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

What are the different types of errors in PHP ?

Here are three basic types of runtime errors in PHP:

1. 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.
2. 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.
3. 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 sql injection ?
SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications

What is x+ mode in fopen() used for?

Read/Write. Creates a new file. Returns FALSE and an error if file already exists

How to find the position of the first occurrence of a substring in a string

strpos() is used to find the position of the first occurrence of a substring in a string

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?

When we need to send query string through url then we should urlencode the value of string variable. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign .
and urldecode covnert string to it original form. so urlencode and urldecode functions are opposite of each other.

What are the different errors in PHP?

In PHP, there are three types of runtime errors, they are:

These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script.
These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed.
Fatal errors:
These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.

Leave a Reply

Your email address will not be published. Required fields are marked *