Our Special Offer - Get 3 Courses at 24,999/- Only. Read more
Hire Talent (HR):+91-9707 240 250

Interview Questions

Top 101+ PHP Interview Questions and Answers

Top 101+ PHP Interview Questions and Answers

Here are the list of most frequently asked PHP Interview Questions and Answers in technical interviews. These questions and answers are suitable for both freshers and experienced professionals at any level. The questions are for intermediate to somewhat advanced PHP professionals, but even if you are just a beginner or fresher you should be able to understand the answers and explanations here we give.

Q1) What is PHP?

PHP is a server side scripting language. It requires a web server to perform execution like Apache, IIS etc. It helps to create a dynamic web applications. PHP is a market leader in-terms of usage. It holds more than 82% of total web market share as of 2015.

Q2) Who is the father of PHP?

Rasmus Lerdorf. He created PHP in the year of 1994.

Q3) Acronym of PHP?

Now PHP stands for “PHP : Hypertext Preprocessor“. Before PHP 4 it was called as “Personal Home Page Tools”.

Q4) Explain the difference between static and dynamic websites?

Static Websites : A webpage or website which was developed by using HTML alone.
Dynamic Websites : A webpage or website which was developed by using any dynamic languages like PHP, ASP.NET, JSP etc

Q5) What is the name of scripting engine in PHP?

ZEND Engine 2 is the name of the scripting engine that powers PHP.

Q6) What are the methods of form submitting in PHP?

We can use GET (or) POST for form submission in PHP.

Q7) What is a session?

A session is a logical object enabling us to preserve temporary data across multiple PHP pages. A PHP session is no different from a normal session. It can be used to store information on the server for future use. However this storage is temporary and is flushed out when the site is closed.

Q8) What is the method to register a variable into a session?

< ?php session_register($name_your_session_here); ?>

Q9) What are the encryption functions in PHP?

md5() – Calculate the md5 hash of a string
sha1() – Calculate the sha1 hash of a string
hash() – Generate a hash value
crypt() – One-way string hashing

Q10)What are the different types of errors in PHP?

There are 3 types of errors in PHP.

Notices : These are the non-critical errors. These errors are not displayed to the users.

Warnings : These are more serious errors but they do not result in script termination. By default, these errors are displayed to the user.

Fatal Errors : These are the most critical errors. These errors may be a cause of immediate termination of script.

Q11) What is the difference between $besant and $$besant?

$besant stores variable data while $$besant is used to store variable of variables.

$besant stores fixed data whereas the data stored in $$besant may be changed dynamically.

Q12) How do you connect MySQL database with PHP?

There are two methods to connect MySQL database with PHP. Procedural and Object Oriented style.

Q13) Difference echo() and print()?

Echo can output one or more string but print can only output one string and always returns 1.

Echo is faster than print because it does not return any value.

Q14) Differentiate between require and include?

Require and include both are used to include a file, but if file is not found include sends warning whereas require sends Fatal error.

Q15) What is the use of count() function in PHP?

count() function is used to count total elements in the array, or something an object.

Q16) What is the difference between session and cookie?

The main difference between session and cookies is that cookies are stored on the user’s computer while sessions are stored on the server side.

Cookies can’t hold multiple variables on the other hand Session can hold multiple variables.

You can manually set an expiry for a cookie, while session only remains active as long as browser is open.

Q17) How can you retrieve a cookie value?

echo $_COOKIE [“cookie_name”];

Q18) What is the use of header() function in PHP?

The header() function is used to send a raw HTTP header to a client. It must be called before sending the actual output. For example, you can’t print any HTML element before using this header function.

Q19) What is the array in PHP?

Array is used to store multiple values in single name. In PHP, it orders in keys and values pairs. It is not a datatype dependent in PHP.

Q20) How can you submit a form without a submit button?

Possible only by using JavaScript. You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.

Q21) Explain the importance of the function htmlentities

The htmlentities() function converts characters to HTML entities.

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

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

Q24) What is Type juggle in php?

Type Juggling means dealing with a variable type. In PHP a variables type is determined by the context in which it is used. If an integer value is assigned to a variable, it becomes an integer.

E.g. $var3= $var1 + $var2

Here, if $var1 is an integer. $var2 and $var3 will also be treated as integers.

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

mysql_fetch_object() returns the result from the database as objects while mysql_fetch_array() returns result as an array. This will allow access to the data by the field names. E.g. using mysql_fetch_object() field can be accessed as $result->fieldname and using mysql_fetch_array() field can be accessed as $result->[‘fieldname’]

Q26) What is the difference between the functions unlink and unset?

The function unlink() is to remove a file, where as unset() is used for destroying a variable that was declared earlier.
unset() empties a variable or contents of file.

Q27) What is Joomla in PHP?

Joomla is an open source content management system. Joomla allows the user to manage the content of the web pages with ease.

Q28) What is the difference between preg_split() and explode()?

preg_split — Split string by a regular expression

< ?php // split the phrase by any number of commas or space characters, // which include ” “, \r, \t, \n and \f $keywords = preg_split(“/[\s,]+/”, “hypertext language, programming”); print_r($keywords); ?>
explode — Split a string by string

< ?php // Example 1 $pizza = “piece1 piece2 piece3 piece4 piece5 piece6″; $pieces = explode(” “, $pizza); echo $pieces[0]; // piece1 echo $pieces[1]; // piece2 ?>

Q29) How to upload files using PHP?

– Select a file from the form using <input type=”file”>
– Specify the path into which the file is to be stored.
– Insert the following code in php script to upload the file.

move_uploaded_file($_FILES[“file”][“tmp_name”], “myfolder/” . $_FILES[“file”][“name”]);

Q30) Describe functions strstr() and stristr()?

Both the functions are used to find the first occurrence of a string. Parameters includes: input String, string whose occurrence needs to be found, TRUE or FALSE (If TRUE, the functions return the string before the first occurrence.)

stristr() is similar to strstr(). However, it is case-insensitive.

Q31) Explain the purpose of output buffering in PHP

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

– Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it’s not being sent to the browser in pieces as PHP processes the HTML.
– All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
– If you’ve ever encountered the message “Warning: Cannot modify header information – headers already sent by (output)” while setting cookies, you’ll be happy to know that output buffering is your answer.

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

Object oriented style:

$datetime1 = new DateTime(‘2009-10-11’);
$datetime2 = new DateTime(‘2009-10-13’);
$interval = $datetime1->diff($datetime2);
echo $interval->format(‘%R%a days’);
Procedural style:

$datetime1 = date_create(‘2009-10-11’);
$datetime2 = date_create(‘2009-10-13’);
$interval = date_diff($datetime1, $datetime2);
echo $interval->format(‘%R%a days’);

Q33) What is the difference between PHP and JavaScript?

While JS is used for client side scripting (except in node.js) and PHP is used for server side scripting.

Simply, JavaScript codes are executed by your web browser, like the catchy animations or simple calculations . Your browser does all the processing. While PHP runs on the server, where your webpage is stored. The server computer does all PHP processing and it sends the result to your browser.

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

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

Difference between require() and require_once(): 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.

Difference between require() and include() is that require() produces a FATAL ERROR if the file you want to include is not found, while include() only produces a WARNING.

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

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

Q37) How php concatenation works?

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;

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

Q39) 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”; }

Q40) 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”

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

Q42) How to declare an array in php?

$arr = array(‘apple’, ‘grape’, ‘lemon’);

Q43) What is use of in_array() function in php ?

in_array() used to checks if a value exists in an array

Q44) How to set cookies in PHP and Retrieve a Cookie Value? Setting Cookie in PHP

setcookie(“cookie_name”, “cookie_value”, time()+(60*60*24*5));

Retriving Cookie in PHP

echo $_COOKIE[“cookie_name”];

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

Create session : session_start();
Set value into session : $_SESSION[‘USER_ID’]=1;
Remove data from a session : unset($_SESSION[‘USER_ID’];

Q46) what types of loops exist in php?

for, while, do while and foreach

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

mysql_fetch_row()
mysql_fetch_array()
mysql_fetch_object()
mysql_fetch_assoc()

Q48) What is the use of explode() function ?

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.

Q49) What is the use of mysql_real_escape_string() function?

It is used to escapes special characters in a string for use in an SQL statement

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

The trim() function removes whitespaces or other predefined characters from both sides of a string.

Q51) How to redirect a page in php?

The following code can be used for it,

header(“Location:page_to_redirect.php”); exit();

Q52) How stop the execution of a php script ?

exit() function is used to stop the execution of a page

Q53) How to find the length of a string?

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

Q54) What is the use of rand() in php?

It is used to generate random numbers. If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.

Q55) What is the use of isset() in php?

This function is used to determine if a variable is set and is not NULL

Q56) Purpose of method attribute in 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.

Q57) 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

Q58) How do you define a constant?

Using define() directive, like define(“CONSTANTNAME”,150)

Q59) How send email using php?

To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can’t send email from localhost. eg : mail($to,$subject,$message,$headers);

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

Q61) How to delete a file from the system

unlink() – deletes the given file from the file system.

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

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

Q63) What is sql injection?

SQL injection is a malicious code injection technique. It exploiting SQL vulnerabilities in Web applications

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

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

Q66) 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 ‘===’.

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

GD library is needed to be able execute image functions.

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

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

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

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

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

Q72) What is the function file_get_contents() usefull for?

file_get_contents() lets reading a file and storing it in a string variable. (Shortcut of fopen + fread + fclose)

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

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

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

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

Any_Question_Returns_Boolean ? What_if_True : What_if_False;

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

:: is used to access static methods that do not require object initialization. (Scope Resolution Operator)

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

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

parent::constructor($value)

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

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

Q81) When sessions ends?

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

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

session_unregister() unregisters the global variable named name from the current session.
The session_unset() function frees all session variables currently registered.

Q83) What does $_SERVER means?

$_SERVER is an array including information created by the web server such as paths, headers, and script locations.

Q84) What does $_FILES means?

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

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

Q86) What does the scope of variables means?

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.

Q87) What is the differences between $a != $b and $a !== $b?

!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).

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

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

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

Q91) What is the default session time in php?

The default session time in php is until closing of browser

Q92) Is it possible to use COM component in PHP?

Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.

Q93) How can we get the browser properties using PHP?

echo $_SERVER[‘HTTP_USER_AGENT’];
(or)
$browser = get_browser();
foreach ($browser as $name => $value) {
echo “$name $value
\n”;
}

Q94) How to store the uploaded file to the final location?

Files in PHP can be uploaded using move_uploaded_file(string filename, string destination);

Q95) What is Constructors and Destructors?

CONSTRUCTOR : PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.
DESTRUCTORS : PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as all references to a particular object are removed or when the object is explicitly destroyed or in any order in shutdown sequence.

Q96) What is MVC?

MVC stands for Model, View, and Controller. PHP MVC is an effective way to manage the code into 3 different layers.

Model: Model represents the information in application.

View: View represents the visual representation of information and data that you have entered in the application.

Controller: Controller is actually how and in which way you want to read the information in application.

Q97) What is meant by nl2br()?

New Line to HTML Break
echo nl2br(“Hello \n World”);
Ans :
Hello
World

Q98) What is the maximum length of a table name, a database name, or a field name in MySQL?

Database name – 64 characters
Table name – 64 characters
Column name (field name) – 64 characters

Q99) Get size of a file using php?

filesize() function returns the size of the specified file.

Q100) Function for merging two arrays?

array_merge() function merges one or more arrays into one array.
(or)
simply we can do
$output = $array1 + $array2;

Q101) What is PDO classes?

The PHP Data Objects (PDO) extension defines a lightweight, consistent interface for accessing databases in PHP. It is a data-access abstraction layer, so no matter what database we use the function to issue queries and fetch data will be same. Using PDO drivers we can connect to database like DB2, Oracle, PostgreSQL etc.

Besant Technologies WhatsApp