Recruiters

PHP Interview Questions and Answers

PHP Interview Questions and Answers


PHP Interview Questions and Answers

Here are some typical PHP interview questions. Select 10 for a typical interview

What is PHP?

The first question in any PHP interview will be: What is PHP? Here it is 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.

How do you 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.

Explain echo vs. print the 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.

What is the difference between $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.

What is the different types of errors you get 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.

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

How do you 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:-

$password = crypt('mypassword');   print $password . “ is the encrypted version of mypassword”;

Explain how urlencode() and urldecode() is used?

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.

$discount ="10.00%";
$url = "http://domain.com/submit.php?disc=".urlencode($discount);
echo $url;
Output: "http://domain.com/submit.php?disc=10%2E00%25".

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:

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

Explain the difference between strongly typed and loosely typed language?

PHP is a loosely typed language. In this type of language variable doesn’t need to be declared before their use. This language converts the data according to its given value. Whereas, in strongly typed language first every type has to be declared (defined) then only it can be used.

Explain what a Persistent Cookie is?

A cookie which is stored in a cookie file permanently on the browser’s computer. 

Explain the differences between DROP a table and TRUNCATE a table.

DROP - It will delete the table and table data. 
TRUNCATE - It will delete data of the table but not the table definition. 

What is the "GET" and "POST" methods?

Both the methods are used to send data to the server. 
GET method - the browser appends the data onto the URL. 
Post method - the data is sent as “standard input.”

Explain the "unlink" and "unset" functions.

unlink() function is for file system handling. It just deletes the file in context.
unset() function is for variable management. It makes a variable undefined

What is the SQL for changing the name of a column in a table?

ALTER TABLE table_name CHANGE old_colm_name new_colm_name 

How long does the default session time in PHP last?

Until closing the browser. 

What is the SQL for creating a database using PHP and MySQL?

By using : mysql_create_db("Database Name") 

How will you find out the value of current session id? 

By using: session_id() 

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.

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

What is a 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 calculate 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 PHP with MySQL connection statements

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.

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

Explain the differences 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.

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.

What IDE is recommended for use 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.

Name the different types of statements 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 script using variables

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> 

Explain what type casting mean

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. 

How do you escape characters

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. 

$string = _Where is Tom\’_s house_;

How do you join 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.

How would you 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.

$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();                          

Published: 1st June 2016 by

Adverts