41 PHP Interview Questions and Answers

Dear Readers, Welcome to PHP interview questions with answers and explanation. These 41 solved PHP questions will help you prepare for technical interviews and online selection tests conducted during campus placement for freshers and job interviews for professionals.

After reading these tricky PHP questions, you can easily attempt the objective type and multiple choice type questions on PHP.

What is PHP?

PHP: Hypertext Preprocessor is open source server-side scripting language that is widely used for web development. 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.

What is PEAR in php?

PEAR(PHP Extension and Application Repository) is a framework and repository for reusable PHP components. PEAR is a code repository containing all kinds of php code snippets and libraries.

PEAR also offers a command-line interface that can be used to automatically install "packages".

Explain how to submit form without a submit button.

We can achieve the above task by using JavaScript code linked to an event trigger of any form field and call the document.form.submit() function in JavaScript code.

Echo vs. print statement.

echo() and print() are language constructs in PHP, both are used to output strings. The speed of both statements is almost the same.

echo() can take multiple expressions whereas print cannot take multiple expressions.

Print return true or false based on success or failure whereas echo doesn't return true or false.

$message vs. $$message in PHP.

$message is a variable with a fixed name. $$message is a variable whose name is stored in $message.

If $message contains "var", $$message is the same as $var.

Explain the different types of errors in PHP.

Notices, Warnings and Fatal errors are the types of errors in PHP

Notices:

Notices represents non-critical errors, i.e. accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all but whenever required, you can change this default behavior.

Warnings:

Warnings are more serious errors but they do not result in script termination. i.e calling include() a file which does not exist. By default, these errors are displayed to the user.

Fatal errors:

Fatal errors are critical errors i.e. calling a non-existent function or class. These errors cause the immediate termination of the script.

Explain the importance of the function htmlentities.

The htmlentities() function converts characters to HTML entities.

What is MIME?

MIME - Multi-purpose Internet Mail Extensions.

MIME types represents a standard way of classifying file types over Internet.

Web servers and browsers have a list of MIME types, which facilitates files transfer of the same type in the same way, irrespective of operating system they are working in.

A MIME type has two parts: a type and a subtype. They are separated by a slash (/).

MIME type for Microsoft Word files is application and the subtype is msword, i.e. application/msword.

Explain how to execute a PHP script using command line.

PHP script using command line can be executed using SAPI (Server Application programming Interface). Using SAPI Command Line Interface the PHP code can be passed to execute directly

Example:
Php –r ‘print_r(get_defined_constanrs());’

From a shell, php –v will display whether the SAPI is CLI or CGI

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

By default the PHP script takes 30secs to execute. This time is set in the php.ini file. This time can be increased by modifying the max_execution_time in seconds. 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.

Explain the purpose of output buffering in PHP.

Output buffering in PHP buffers a scripts output. This buffer can be edited before returning it to the client. Without output buffering, PHP sends data to the web server as soon as it is ready. Output buffering "send" cookies at any point in the script. Cookies do not have to be necessarily sent near the start of page. Output buffers are stackable and hence sending to output is by choice.

Describe session in PHP.

When a user logs in an application, his details are usually stored in a session variable. This information is available to all pages in one application. Sessions in PHP work using a unique id for each visitor.

How can we know the number of days between two given dates using PHP?

The start date and end date can be first found as shown below:
$date1= strotime($start_date);
$date2= strotime($end_date);
$date_diff = (($date1)- ($date2)) / (60*60*24)

Write the statements that are used to connect PHP with MySQL

The statements that can be used to connect PHP wil MySQL is:
<?
$conn = mysql_connect('localhost');
echo $conn;
?>
This statement gets the resource of the localhost. There are other different ways with which you can connect to the database and they are as follows:
<?
mysql_connect('db.domain.com:33306','root','user');
mysql_connect('localhost:/tmp/mysql.sock');
mysql_connect('localhost','rasmus','foobar',
true,MYSQL_CLIENT_SSL|MYSQL_CLIENT_COMPRESS);
?>

How to use HTTP Headers inside PHP? Write the statement through which it can be added?

HTTP headers can be used in PHP by redirection which is written as:
<?header('Location: http://www.php.net')?>

The headers can be added to HTTP response in PHP using the header(). The response headers are sent before any actual response being sent. The HTTP headers have to be sent before taking the output of any data. The statement above gets included at the top of the script.

Why PHP is also called as Scripting language?

PHP is basically a general purpose language, which is used to write scripts. Scripts are normal computer files that consist of instructions written in PHP language. It tells the computer to execute the file and print the output on the screen. PHP is used for webpages and to create websites, thus included as scripting language.

Why many companies are switching their current business language to PHP? Where PHP basically used?

PHP is rapidly gaining the popularity and many companies are switching their current language for this language. PHP is a server side scripting language. PHP executes the instructions on the server itself. Server is a computer where the web site is located. PHP is used to create dynamic pages and provides faster execution of the instructions.

What is the use of PEAR in php?

PEAR is known as PHP Extension and Application Repository. It provides structured library to the PHP users and also gives provision for package maintenance.

What is the difference between PHP and JavaScript?

The difference lies with the execution of the languages. PHP is server side scripting language, which means that it can’t interact directly with the user. Whereas, JavaScript is client side scripting language, that is used to interact directly with the user.

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

The main difference between $message and $$message is that former one is a simple variable and later is a reference variable. $message is a variable with a fixed name and it consists of a fixed value. $$messages contains the variable itself.

What does ODBC do in context with PHP?

PHP supports many databases like dBase, Microsft SQL Server, Oracle, etc. But, it also supports databases like filePro, FrontBase and InterBase with ODBC connectivity. ODBC stands for Open Database connectivity, which is a standard that allows user to communicate with other databases like Access and IBM DB2.

Why PHP is sometimes called as embedded scripting language?

PHP is a high level language which is used to allow users to write and understand it in human readable form and also use an interpreter to interpret the code which user write for the computer. PHP is used as an embedded scripting language for the web. PHP is embedded in HTML code. HTML tags are used to enclose the PHP language. HTML is used and PHP is code written in it in the same way as you write JavaScript in HTML.

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

require() includes and evaluates a specific file, if the file is not found then it shows a Fatal Error.

require_once() includes only the file which is not being included before. It is used to be recommended for the files where you have lots of functions stored.

include() includes the file, even if the file is not found, but it gives a warning to the user to include().

How the web server interprets PHP and interacts with the client?

After installing and configuring the PHP, the web When PHP is installed, the Web server looks for PHP code that is embedded in HTML file with its extension. The extensions which are used are .php or .phtml. When web server receives a request for the file with an appropriate extension, HTML statements are processed and PHP statements are executed on the server itself. When the processing gets over the output is being shown in HTML statements.

PHP being an open source is there any support available to it?

PHP is an open source language, and it is been said that it has very less support online and offline. But, PHP is all together a different language that is being developed by group of programmers, who writes the code. There is lots of available support for PHP, which mostly comes from developers and PHP users.

What are the steps involved to run PHP?

The steps which are involved and required to run PHP is as follows:

1. Set up the web environment.

2. Set up the web servers. There are many web servers that are available and the mostly used is Apaches which automatically remains installed with linux distribution and on windows it is easy to install. There are other servers like IIS (Internet information server) provided by Microsoft can be used to set up the web environment.

3. Install the web server and PHP

4. Update and administer the system for changes.

What is the difference between echo, print and printf()?

Echo is the basic type used to print out a string. It just shows the content of the message written using it. It can have multiple parameters as well. print is a construct, it returns TRUE on successful output and FALSE there is no output. It can’t have multiple parameters.

Printf() is a function, and not be used as a construct. It allows the string output to be formatted. It is the slowest medium to print the data out.

Why IDE is recommended for use while programming with PHP?

IDE stands for Integrated Development environment; it is a framework for developing applications. It includes programming editor where you can edit and write the development programs. The features of IDE are as follows:

1. Debugging: this is the feature which is used to debug or find the bugs in a program
2. Preview: this is the feature which allow instant preview of the program you are writing
3. Testing: this is the features that includes built in testing features through which you can check your scripts
4. FTP: through this you can upload and download the file while connecting to the server.
5. Project management: it organizes scripts into projects; manages the files in the project; includes file checkout and check-in features.
6. Backups: it creates backups automatically of your Web site at periodic intervals.

How PHP statement is different from PHP script?

The difference between PHP statement and PHP script is that statements are set of instructions that tell PHP to perform an action. PHP script consists of a series of PHP statements that it uses for execution. PHP executes statements one at a time till it reaches the end of the script. Example is as follows:
PHP statement: echo “Hi”;

PHP script:
if (time = midnight)
{
   put on pajamas;
   brush teeth;
   go to bed;
}

What are the different types of statements that are present in PHP?

There are four kinds of PHP statements that are present. They are as follows:

Simple statement- these are the echo statements and end with a semicolon (;). PHP ignores white spaces between simple statements. Until it finds a semicolon it reads the statement.

Complex/Conditional statements: these are the statements which deal with certain conditions that have to be executed to meet certain specific requirements. These are if and else block or switch statements. PHP reads the complete statement and doesn’t stop at the first semicolon it encounters. It looks for starting and ending braces to end the execution.

Looping statements: statements that are repeated in a block. The feature that enables you to execute the statements repeatedly is called as loop. For example: for loop, while loop, do..while loop.

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

By the use of void set_time_limit(int seconds)

Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Write a Hello world program using variable?

To write the hello world program in PHP using variable you need to know the tags that are used in HTML and the PHP coding which is as follows:
<html>
<head><title>Hello World Script using Variable</title></head>
<body>
<?php
$salutation = “Hello World!”;
echo “<p>$salutation</p>”;
?>
</body>
</html>

How many different types of messages available in PHP?

1. Error message: is received when the script has some problem that is preventing it from running correctly. The message consists of the possible solution or identification of the problem. Ex: Parse error: occurs when there is something gets missed while writing the script.

2. Warning message: is received when the script find out some problem that doesn’t allow the script to run. These messages are not of very high priority but quite essential to show that there is something wrong with the script. Ex: if you write print_r() instead of print_r($varname) then a warning will occur like this:

Warning: print_r() expects at least 1 parameter, 0 given
The script will execute in continuation.

3. Notice: is received when there is a condition where a script might have an error or may be it is working. Ex: echo variables that don’t exist.

What does type casting mean in PHP? Explain with an example?

PHP automatically store the data and interprets according to itself. Type casting is a way to assign the variable according to your need and requirement and not allowing PHP to assign it automatically. To specify the type, it can be used like:
$newint = (int) $var1;
$newfloat = (float) $var1;
$newstring = (string) $var1;

The value in the variable on the right side of the equal sign is stored in the variable on the left side as the specified type.

How error handling is being handled by PHP?

Error handling is very important in every programming language. PHP uses the trigger to print the error in a program. The example statement is given below:
If ($height_of_door > $height_of_house)
{
    trigger_error(“Impossible condition”,E_USER_ERROR);
}

The E_USER_ERROR in the statement tells PHP that the condition is an error. Impossible condition is a string message which is displayed when an error is encountered.
If the condition comes out to be true then the following message is displayed:

Fatal error: Impossible condition

E_USER_WARNING or E_USER_NOTICE can be used instead of E_USER_ERROR, to have PHP treat the condition as a warning or notice. Own statements can be written to perform error handling actions such as send a message, log a message or stop the script.

For example:
If ($height_of_door > $height_of_house)
{
    echo “This is impossible<br>”;
    exit();
}

If $height_of_door is larger than $height_of_house, the message is echoed, and exit() stops the script.
Die statement can be used to display an error message when a function fails.

What are escaping characters? Explain with an example?

Special characters are the characters that have some special meaning attached to it. Example is $, #, % etc. A backslash (\) before the special symbol is known as escaping characters. For example, two strings produce the same output:
$string = ‘The variable name is $var1’;
$string = “The variable name is \$var1”;

The output from either string is the following:

The variable name is $var1

Suppose you want to store a string as follows:

$string = _Where is Tom’_s house_;
echo $string;

The sting can be interpreted by PHP by putting a backslash (\) in front of the single quote. The backslash tells PHP that the single quote does not have any special meaning; it’s just an apostrophe.

Example:
$string = _Where is Tom\’_s house_;

Write a program to show the joining of two strings in PHP?

Two strings can be joined together by the use of a process called as concatenation. A dot (.) operator is used for this purpose. Example is as follows:
$string1 = _Hello_;
$string2 = _World!_;
$stringall = $string1.$string2;
echo $stringall;

What are the different components used in PHP for formatting?

The components that are used in PHP for formatting are as follows:

1. %: it tells the start of the formatting instruction.

2. Padding character (pad): is used to fill out the string when the value to be formatted is smaller than the width assigned. Pad can be a space, a 0, or any character preceded by a single quote (‘).

3. -: A symbol meaning to left-justify the characters. If this is not included, the characters are right-justified.

4. width: The number of characters to use for the value. If the value doesn’t fill the width, the padding character is used to pad the value. For example, if the width is 5, the padding character is 0, and the value is 1, the output is 00001.

5. dec: The number of decimal places to use for a number. This value is preceded by a decimal point.

6. type: The type of value. Use s(string) for string, f (float) for numbers that you want to format with decimal places.

What is the use of super-global arrays in PHP?

Super global arrays are the built in arrays that can be used anywhere. They are also called as auto-global as they can be used inside a function as well. The arrays with the longs names such as $HTTP_SERVER_VARS, must be made global before they can be used in an array. This $HTTP_SERVER_VARS check your php.ini setting for long arrays.

What is the use of $_Server and $_Env?

$_SERVER and $_ENV arrays contain different information. The information depends on the server and operating system being used. Most of the information can be seen of an array for a particular server and operating system. The syntax is as follows:
foreach($_SERVER as $key =>$value)
{
echo “Key=$key, Value=$value\n”;
}

What is the difference between $argv and $argc? Give example?

To pass the information into the script from outside, help can be taken from the PHP CLI (Command line interface) method. Suppose addition of two numbers has to be passed to PHP then it can be passed like this on the command line:

php add.php 2 3

Here the script name is add.php, and 2 and 3 are the numbers that has to be added by the script. These numbers are available inside the script in an array called
$argv. This array contains all the information on the command line; the statement is stored as follows:

$argv[0]=add.php
$argv[1]=2
$argv[2]=3

So, $argv always contains at least one element — the script name.
Then, in your script, you can use the following statements:

$sum = $argv[1] + $argv[2];
echo $sum;
$argc is a variable that stores the numbers of elements in $argv. $argc is equal to at least 1, which is saved for the name of the script.

Example is $argc=3 using the above statements.

Write a statement to show the joining of multiple comparisons in PHP?

PHP allows multiple comparisons to be grouped together to determine the condition of the statement. It can be done by using the following syntax:

comparison1 and|or|xor comparison2 and|or|xor comparison3 and|or|xor.

The operators that are used with comparisons are as follows:

1. and: result in positive when both comparisons are true.
2. or: result in positive when one of the comparisons or both of the comparisons are true.
3. xor: result in positive when one of the comparisons is true but not both of the comparisons.

Example:
$resCity == “Reno” or $resState == “NV” and $name == “Sally”

How to create reusable code in PHP?

Applications created in PHP often perform the same task in same script or in different scripts. To create a reusable code functions are used. Functions are group of PHP statements that perform a specific task.

Example:

A header and footer can be created for all the web pages which has to be used again and again.
echo ‘<img src=”greenrule.jpg” width=”100%” height=”7” />
<address>My Great Company
<br />1234 Wonderful Rd.
<br />San Diego, CA 92126
</address></font>
<p>or send questions to
<a href=”mailto:sales@company.com”>sales </a>
<img src=”greenrule.jpg” width=”100%” height=”7” />’;

Instead of typing header and footer for each page, a function can be created and used to add footer and header in every page. The function can be named as:

add_footer();
add_header();
PHP - What is PHP?
PHP - PHP (Hyper text Pre Processor) is a scripting language commonly used for web applications.....
PHP Session - What Is a Session in PHP?
PHP Session - A PHP session is no different from a normal session. It can be used to store information on the server for future use....
PHP message - Explain the difference between $message and $$message?
PHP message - $message is used to store variable data. $$message can be used to store variable of a variable......
Post your comment
Discussion Board
question
help me to get following accurate answer


define ("ab" ,10);
define("cd" ,1);
define("ef2" ,2);
define("gh3" ,3);

echo 'ab' . "
;
echo constant ( 'ab' );

echo 'cd' . "
";
echo constant ('cd');

echo 'ef2' ."
";
echo constant ("ef2");

echo 'gh3' ."
";
echo constant ("gh3");

?>
Manjunath 06-2-2015
session
session are used to store information on future used
puneet tiwari 09-9-2014
php1
nice
abc 04-30-2014
php
very nice
abc 04-30-2014
PHP interview questions and answers
How can I execute a PHP script using command line?

You can execute a PHP script by running the Command line interface program, in which you can enter the PHP script file as an argument. If the file is made for the web interface then it may not execute properly using command line. Command line allows faster execution of the statements and gives faster results.

How can we encrypt the password using PHP?

crypt() function is used to create one way encryption. It takes one input string and one optional parameter. The function look is defined as: crypt (input_string, salt), where input_string consists of the string which has to be encrypted and salt is an optional parameter. PHP uses DES for encryption. The format is as follows:-

<?php

$password = crypt('mypassword');

print $password . “ is the encrypted version of mypassword”;

?>

What are different types of Runtime Errors in PHP?

There are three types of Runtime Errors in PHP. They are as follows:-

- Notices: These are trivial, non-critical errors eg: undefined variable
- Warnings: These are serious errors eg. Including non-existing file
- Fatal errors: These are critical errors eg. Calling of non-existent function.
Rohit Sharma 12-11-2011
PHP interview questions and answers
What does a special set of tags do in PHP?

Special set of tags allows you to display the output directly to the browser. The special set of tags are represented as <?php..(your statements)..?>. They allow you to write your code for execution and representation, that you want to display and execute. The example is as follows to explain it more:

<html>
<body>

<?php echo "Hello world"; ?> // it will print the Hello world directly to browser

</body>
</html>

Define urlencode() and urldecode() used in PHP?

urlencode() returns the URL encoded version of given string. For URL encoding string values are used in the queries to be passed as URL. Whereas,

urldecode() returns the URL decoded string (original string) which will be decoded by taking the already encoded string.

Example is as follows:

$discount ="10.00%";

$url = "http://domain.com/submit.php?disc=".urlencode($discount);

echo $url;

Output: "http://domain.com/submit.php?disc=10%2E00%25".
Rohit Sharma 12-11-2011
PHP interview questions and answers
What is the difference between $message and $$message?

The only difference between $message and $$message is that, $message is a normal variable and $$message is variable to variable. The difference in functioning is shown below:

When declaring a variable in PHP the variable gets declared like this

$message //which is simply a variable

To store the data to assign the value to it we write like

$message= “ride”; //assigned the string to the variable

echo $message; // it will print the value

Whereas if you want to display the variable to variable then you use

$var="Hello";

$message="var";

echo $message; //print var

echo $$message; //print Hello.

What Is a Persistent Cookie?

Persistent cookie is a cookie which is permanently stored on user’s computer in a cookie file. They are used for tracking the user information of the users who are browsing from a very long time. They also have the drawbacks of being unsecure, as user can see the cookies which are saved on the computer.
Rohit Sharma 12-11-2011
PHP interview questions and answers
What is a PHP Session?

PHP session allows you to store the user session, like their information on server for faster access and for later use like username, IP addresses, their actions etc. The information which is saved is temporary and can be deleted after the user is no longer active. Example of starting a PHP session is as follows:

<?php
session_start(); // start up your PHP session!
?>

What is meant by PEAR in php? What is the purpose of it?

PEAR stands for "PHP Extension and Application Repository". As the name suggests, it gives advanced functionality to the PHP language and include many applications which can be used on fly. The purpose of it is as follows:-

- Open source structured library for PHP users
- Code distribution and package maintenance system
- Standard style for code written in PHP
Rohit Sharma 12-11-2011