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.
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.
Rasmus Lerdorf. He created PHP in the year of 1994.
Now PHP stands for “PHP : Hypertext Preprocessor“. Before PHP 4 it was called as “Personal Home Page Tools”.
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
ZEND Engine 2 is the name of the scripting engine that powers PHP.
We can use GET (or) POST for form submission in PHP.
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.
< ?php session_register($name_your_session_here); ?>
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
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.
$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.
There are two methods to connect MySQL database with PHP. Procedural and Object Oriented style.
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.
Require and include both are used to include a file, but if file is not found include sends warning whereas require sends Fatal error.
count() function is used to count total elements in the array, or something an object.
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.
echo $_COOKIE [“cookie_name”];
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.
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.
Possible only by using JavaScript. You can use JavaScript submit() function to submit the form without explicitly clicking any submit button.
The htmlentities() function converts characters to HTML entities.
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.
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.
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.
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’]
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.
Joomla is an open source content management system. Joomla allows the user to manage the content of the web pages with ease.
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 ?>
– 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”]);
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.
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.
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’);
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.
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.
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().
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.
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;
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.
$_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”; }
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”
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 .
$arr = array(‘apple’, ‘grape’, ‘lemon’);
in_array() used to checks if a value exists in an array
setcookie(“cookie_name”, “cookie_value”, time()+(60*60*24*5));
Retriving Cookie in PHP
echo $_COOKIE[“cookie_name”];
Create session : session_start();
Set value into session : $_SESSION[‘USER_ID’]=1;
Remove data from a session : unset($_SESSION[‘USER_ID’];
for, while, do while and foreach
mysql_fetch_row()
mysql_fetch_array()
mysql_fetch_object()
mysql_fetch_assoc()
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.
It is used to escapes special characters in a string for use in an SQL statement
The trim() function removes whitespaces or other predefined characters from both sides of a string.
The following code can be used for it,
header(“Location:page_to_redirect.php”); exit();
exit() function is used to stop the execution of a page
strlen() function used to find the length of a string
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.
This function is used to determine if a variable is set and is not NULL
“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.
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
Using define() directive, like define(“CONSTANTNAME”,150)
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);
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.
unlink() – deletes the given file from the file system.
session_id() – function returns the session id for the current session.
SQL injection is a malicious code injection technique. It exploiting SQL vulnerabilities in Web applications
PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.
‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.
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 ‘===’.
GD library is needed to be able execute image functions.
imagetypes() gives the image format and types supported by the current version of GD-PHP.
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
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.
This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.
file_get_contents() lets reading a file and storing it in a string variable. (Shortcut of fopen + fread + fclose)
The function mysql_num_rows() returns the number of rows in a result set.
A static variable is defined within a function only the first time and its value can be modified during function calls.
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.
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;
:: is used to access static methods that do not require object initialization. (Scope Resolution Operator)
No, a parent constructor have to be called explicitly as follows:
parent::constructor($value)
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
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.
Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().
session_unregister() unregisters the global variable named name from the current session.
The session_unset() function frees all session variables currently registered.
$_SERVER is an array including information created by the web server such as paths, headers, and script locations.
$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.
We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.
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.
!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).
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.
Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.
The default session time in php is until closing of browser
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.
echo $_SERVER[‘HTTP_USER_AGENT’];
(or)
$browser = get_browser();
foreach ($browser as $name => $value) {
echo “$name $value
\n”;
}
Files in PHP can be uploaded using move_uploaded_file(string filename, string destination);
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.
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.
New Line to HTML Break
echo nl2br(“Hello \n World”);
Ans :
Hello
World
Database name – 64 characters
Table name – 64 characters
Column name (field name) – 64 characters
filesize() function returns the size of the specified file.
array_merge() function merges one or more arrays into one array.
(or)
simply we can do
$output = $array1 + $array2;
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.