PHP INTERVIEW QUESTIONS
INTERVIEW QUESTIONS &
ANSWERS
This file is compiled to suit the needs for those who intend to prepare for interview calls on PHP.
Like us on FB:
https://www.facebook.com/alphaAinsteinResearch
Connect to our group on FB:
https://www.facebook.com/groups/1567359346890939
2
1. What is PHP?
Answer: PHP is a web language based on scripts that allows developers to dynamically create
generated web pages.
PHP is a server side scripting language commonly used for web applications. PHP has many
frameworks and CMS for creating websites. Even a non-technical person can create sites using its
CMS, WordPress, Commerce are the famous CMS of PHP. It is also an object oriented programming
language like java, C-sharp etc.
2. What does the initials of PHP stand for?
Answer: PHP means PHP: Hypertext Preprocessor.
3. Which programming language does PHP resemble to?
Answer: PHP syntax resembles Perl and C
4. What does PEAR stand for?
Answer: PEAR means PHP Extension and Application Repository. it extends PHP and provides a
higher level of programming for web developers.
5. What is Open Source Software?
Answer: Software in which the source codes are freely used, modify, and shared by anyone are
called Open Source Software. These can also be distributed under licenses that adhere with the Open
Source Definition.
6. What is the difference between include(), include_once() and require_once() Answer: The
include() statement includes and evaluates a specified line i.e. it will include a file based in the given
path. require() does the same thing expect upon failure it will generate a fatal error and halt the
script whereas include() will just give a warning and allow script to continue. require_once() will
check if the file already has been included and if so it will not include the file again.
7. Differences between GET, POST and REQUEST methods?
Answer: GET and POST are used to send information from client browser to web server. In case of
GET the information is send via GET method in name/value pair and is URL encoded. The default
GET has a limit of 512 characters. The POST method transfers the information via HTTP Headers. The
POST method does not have any restriction in data size to be sent. POST is used for sending data
securely and ASCII and binary types data. The $_REQUEST contains the content of both $_GET,
$_POST and $_COOKIE.
3
8. What are the different errors in PHP?
Answer: There are 4 basically types of error.
Parse Error Commonly caused due to syntax mistakes in codes e.g. missing semicolon, mismatch
brackets.
Fatal Error These are basically run time errors which are caused when you try to access what cant
be done. E.g. accessing a dead object, or trying to use a function that hasnt been declared.
Warning Error These occurs when u try to include a file that is not present, or delete a file that is
not on the server. This will not halt the script; it will give the notice and continue with the next line of
the script.
Notice Error These errors occur when you try to use a variable that hasnt been declared, this will
not halt the script, It will give the notice and continue with the next line of the script.
9. What is session and why do we use it?
Answer: Session is a super global variable that preserve data across subsequent pages. Session
uniquely defines each user with a session ID, so it helps making customized web application where
user tracking is needed.
10. What is cookie and why do we use it?
Answer: Cookie is a small piece of information stored in client browser. It is a technique used to
identify a user using the information stored in their browser (if already visited that website). Using
PHP we can both set and get COOKIE.
11. How we know the total number of elements of Array?
Answer: There are two methods through which we can know the total number of elements:
sizeof($array_var) count($array_var)
12. What is the difference between explode() and split() functions?
Answer: Split function splits string into array by regular expression. Explode splits a string into array
by string.
13. How to strip whitespace (or other characters) from the beginning and end of a string?
Answer: The trim() function removes whitespaces or other predefined characters from both sides of
a string.
14. How to set a page as a home page in a php based site?
Answer: index.php is the default name of the home page in php based sites.
15. How to find the length of a string?
Answer: strlen() function used to find the length of a string.
16. what is the use of isset() in php?
Answer:This function is used to determine if a variable is set and is not NULL.
17. What is the use of "ksort" in php?
Answer: It is used for sort an array by key in reverse order
18. How to delete a file from the system
Answer:Unlink() deletes the given file from the file system
19. What is PEAR in php?
Answer: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".
$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.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.
20. Explain how to submit form without a submit button.
Answer:
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 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.
21. What is the use of PEAR in php?
Answer: PEAR is known as PHP Extension and Application Repository. It provides structured library
to the PHP users and also gives provision for package maintenance.
22. What is the difference between PHP and JavaScript?
Answer: The difference lies with the execution of the languages. PHP is server side scripting
language, which means that it cant interact directly with the user. Whereas, JavaScript is client side
scripting language, that is used to interact directly with the user.
23. What is the difference between $message and $$message?
Answer: 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.
6
24. What is the use of "echo" in php?
Answer: It is used to print a data in the webpage, Example: <?php echo 'Car insurance'; ?> , The
following code print the text in the webpage
25. How to include a file to a php page?
Answer: We can include a file using "include() " or "require()" function with file path as its
parameter.
26.What's the difference between include and require?
Answer: If the file is not found by require(), it will cause a fatal error and halt the execution of the
script. If the file is not found by include(), a warning will be issued, but execution will continue.
27. require_once(), require(), include().What is difference between them?
Answer: 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.
28. Differences between GET and POST methods?
Answer: 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.
29. How to declare an array in php?
Answer: Eg : var $arr = array('apple', 'grape', 'lemon');
30. What is the use of 'print' in php?
Answer: This is not actually a real function, It is a language construct. So you can use with out
parentheses with its argument list.
Example print('PHP Interview questions'); print 'Job
Interview ');
31. What is use of in_array() function in php ?
Answer: in_array used to checks if a value exists in an array
32. What is use of count() function in php ?
Answer: count() is used to count all elements in an array, or something in an object
33.Whats the difference between include and require?
Answer: Its how they handle failures. If the file is not found by require(), it will cause a fatalerror
and halt the execution of the script. If the file is not found by include(), a warning will be issued, but
execution will continue.
34.What is the difference between Session and Cookie?
Answer: The main difference between sessions and cookies is that sessions are stored on the server,
and cookies are stored on the users computers in the text file format. Cookies cannot hold multiple
variables, But Session can hold multiple variables. We can set expiry for a cookie, the session only
remains active as long as the browser is open. Users do not have access to the data you stored in
Session, since it is stored in the server. Session is mainly used for login/logout purpose while cookies
using for user activity tracking
35. How to set cookies in PHP?
Answer: Setcookie("sample", "ram", time()+3600);
36. How to Retrieve a Cookie Value?
Answer: eg : echo $_COOKIE["user"];
37. How to create a session? How to set a value in session ? How to Remove data from a
session?
Answer: Create session : session_start();
Set value into session : $_SESSION['USER_ID']=1;
Remove data from a session : unset($_SESSION['USER_ID'];
38. Is variable name case sensitive? could we start a variable with number like
$4name? What is the difference between $name and $$name?
Answer: Yes, variable name case sensitive and we cant start a variable with number like $4name as
A valid variable name starts with a letter or underscore, followed by any number of letters, numbers,
or underscores, whereas $$ is variable of variable $name is variable whereas $$name is variable of
variable
like $name=sonia and $$name=singh so $sonia value is singh.
39. How do you connet mysql database with PHP ?
Answer: We can connect Mysql Database with PHP using both Procedural and Object oriented style
like below
$link = mysqli_connect(localhost, username, password, dbofpcds);
$mysqli = new mysqli(localhost, username, password, dbname); and in old type
of connectivity were
$link = mysql_connect(localhost, username, password); mysql_select_db(database,$link);
8
40. In how many ways we can retrieve the data in the result set of MySQL using PHP? What is
the difference between mysql_fetch_object and mysql_fetch_array ?
Answer: we can retrieve the data in the result set of MySQL using PHP in 4 Ways
1. mysqli_fetch_row >> Get a result row as an enumerated array
2. mysqli_fetch_array >> Fetch a result row as associative and numeric array
3.mysqli_fetch_object >> Returns the current row of a result set as an object
4. mysqli_fetch_assoc >> Fetch a result row as an associative array mysqli_fetch_object() is
similar to mysqli_fetch_array(), with one difference - an object is returned, instead of an array.
Indirectly, that means that
we can only access the data by the field names, and not by their offsets (numbers
are illegal property names).
41. What are the differences between Get and post methods.
Answer: There are some difference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for request
But in POST method unlimited data can we send
2. when we use GET method requested data show in url but
Not in POST method so POST method is good for send sensetive request
42. How can we extract string pcds.co.in from a string http://[email protected]
using regular expression of PHP?
Answers: preg_match(/^http:\/\/.+@(.+)$/,http://[email protected],
$matches);
echo $matches[1];
43. How can we create a database using PHP and MySQL? Answer:We
can create MySQL database with the use of mysql_create_db(Database
Name)
44. What are the differences between require and include?
Answer:Both include and require used to include a file but when included file not found
Include send Warning whereas Require send Fatal Error.
45. Can we use include (xyz.PHP) two times in a PHP page index.PHP? Answer: Yes, we can
use include(xyz.php) more than one time in any page. but it create a problem when xyz.php file
contain some functions declaration then error will come for already declared function in this file else
not a problem like if you want to show same content two time in page then must include it two time
not a problem.
9
46. What are the different tables(Engine) present in MySQL, which one is default?
Answer: Following tables (Storage Engine) we can create
1. MyISAM (The default storage engine IN MYSQL Each MyISAM table is stored on disk in three
files. The files have names that begin with the table name and have an extension to indicate the file
type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index
file has an .MYI (MYIndex) extension.)
2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has
commit, rollback, and crash-recovery capabilities to protect user data.)
3. Merge
4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in
memory. Formerly, these were known as HEAP tables.
MEMORY is the preferred term, although HEAP remains supported for backward compatibility. )
5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional
storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater
chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on
transactions)
6. EXAMPLE
7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather
than in local tables. )
8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes
in a very small footprint. )
9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)
10. BLACKHOLE (The BLACKHOLE storage engine acts as a black hole that accepts data but
throws it away and does not store it. Retrievals always return an empty result)
47. What is use of header() function in php ?
Answer: The header() function sends a raw HTTP header to a client.We can use header() function for
redirection of pages. It is important to notice that header() must be called before any actual output is
seen..
48. How can I execute a PHP script using command line?
Answer: Just run the PHP CLI (Command Line Interface) program and provide the PHP
script file name as the command line argument.
10
49. Suppose your Zend engine supports the mode <? ?> Then how can you configure
your PHP Zend engine to support <?PHP ?> mode ?
Answer: In php.ini file:
set short_open_tag=on
to make PHP support
50. Shopping cart online validation i.e. how can we configure Paypal, etc.? Answer: Nothing
more we have to do only redirect to the payPal url after submitting all information needed by paypal
like amount, address etc.
51. What is meant by nl2br()?
Answer: Inserts HTML line breaks (<BR />) before all newlines in a string.
52. What is htaccess? Why do we use this and Where?
Answer: .htaccess files are configuration files of Apache Server which provide a way to make
configuration changes on a per-directory basis. A file, containing one or more configuration
directives, is placed in a particular document directory, and the directives apply to that directory,
and all subdirectories thereof.
53. How we get IP address of client, previous reference page etc ?
Answer:By using $_SERVER['REMOTE_ADDR'],
$_SERVER['HTTP_REFERER'] etc.
54. What are the reasons for selecting lamp (Linux, apache, MySQL, PHP) instead of
combination of other software programs, servers and operating systems?
Answer:All of those are open source resource. Security of Linux is very very more than
windows. Apache is a better server that IIS both in functionality and security. MySQL is
world most popular open source database. PHP is more faster that asp or any other
scripting language.
55. How can we encrypt and decrypt a data present in a MySQL table using MySQL?
Answer:AES_ENCRYPT () and AES_DECRYPT ()
56. How can we encrypt the username and password using PHP?
Answer:The functions in this section perform encryption and decryption, and compression and
uncompression:
11
57. How can we get the properties (size, type, width, height) of an image using PHP image
functions?
Answer: To know the Image type use exif_imagetype () function To know the
Image size use getimagesize () function
To know the image width use imagesx () function To know
the image height use imagesy() function
58. How can we get the browser properties using PHP? Answer:
By using
$_SERVER[HTTP_USER_AGENT] variable.
59. What is the maximum size of a file that can be uploaded using PHP and how
can we change this?
Answer: By default, the maximum size is 2MB. and we can change the following setup at
php.iniupload_max_filesize = 2M
60. How can we increase the execution time of a PHP script?
Answer: by changing the following setup at php.inimax_execution_time = 30; Maximum execution
time of each script, in seconds
61. How can we take a backup of a MySQL table and how can we restore it. ?
Answer: To backup: BACKUP TABLE tbl_name[,tbl_name] TO /path/to/backup/directory
RESTORE TABLE tbl_name[,tbl_name] FROM /path/to/backup/directorymysqldump: Dumping
Table Structure and DataUtility to dump a database or a collection of database for backup or for
transferring the data to another SQL server (not necessarily a MySQL server). The dump will contain
SQL statements to create the table and/or populate the table. -t, no- create-info Dont write table
creation information (the CREATE TABLE statement). -d, no-data Dont write any row information for
the table. This is very useful if you just want to get a dump of the structure for a table.
62. How can we optimize or increase the speed of a MySQL select query? Answer:
First of all instead of using select * from table1, use select column1, column2, column3.. from
table1
Look for the opportunity to introduce index in the table you are querying.
use limit keyword if you are looking for any specific number of rows from the result set.
12
63. How many ways can we get the value of current session id? Answer:
session_id() returns the session id for the current session.
64. How can we destroy the session, how can we unset the variable of a session?
Answer: session_unregister Unregister a global variable from the current session
session_unset Free all session variable
65. How can we destroy the cookie?
Answer: Set the cookie in past.
66. How many ways we can pass the variable through the navigation between the pages?
Answer:
GET/QueryString
POST
67. What is the difference between ereg_replace() and eregi_replace()? Answer:
eregi_replace() function is identical to ereg_replace() except that this ignores case distinction
when matching alphabetic characters.eregi_replace() function is identical to ereg_replace()
except that this ignores case distinction when matching alphabetic characters.
68. What are the different functions in sorting an array? Answer:
Sort(), arsort(),
asort(), ksort(), natsort(),
natcasesort(), rsort(), usort(),
array_multisort(), and
uksort().
69. How can we know the count/number of elements of an array?
Answer: 2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)
13
70. What is the PHP predefined variable that tells the What types of images that
PHP supports?
Answer: Though i am not sure if this is wrong or not, With the exif extension you are able to work
with image meta data.
71. How can I know that a variable is a number or not using a JavaScript? Answer: bool
is_numeric ( mixed var) Returns TRUE if var is a number or a numeric string, FALSE otherwise. Or
use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.
72. List out some tools through which we can draw E-R diagrams for mysql.
Answer:
Case Studio
Smart Draw
73. How can I retrieve values from one database server and store themin other database
server using PHP?
Answer: We can always fetch from one database and rewrite to another. Here is a nice solution of it.
$db1 = mysql_connect(host,user,pwd);
mysql_select_db(db1?, $db1);
$res1 = mysql_query(query,$db1);
$db2 = mysql_connect(host,user,pwd);
mysql_select_db(db2?, $db2);
$res2 = mysql_query(query,$db2);
At this point you can only fetch records from you previous Result Set, i.e. $res1 But you cannot
execute new query in $db1, even if you supply the link as because the link was overwritten by the
new db.so at this point the following script will fail
$res3 = mysql_query(query,$db1); //this will fail. So how to solve that? take a look below.
$db1 = mysql_connect(host,user,pwd);
mysql_select_db(db1?, $db1);
$res1 = mysql_query(query,$db1);
$db2 = mysql_connect(host,user,pwd, true); mysql_select_db(db2?, $db2);
$res2 = mysql_query(query,$db2);
So mysql_connect has another optional boolean parameter whichindicates whether a link will be
created or not. As we connect to the $db2 with this optional parameter set to true, so both link
willremain live. Now the following query will execute successfully.
$res3 = mysql_query(query,$db1);
14
74. List out the predefined classes in PHP?
Answer: Directory stdClass
PHP_Incomplete_Class
exception
php_user_filter
75. How can I make a script that can be bi-language (supports English, German)?
Answer: You can maintain two separate language file for each of the language. All the labels are
putted in both language files as variables and assign those variables in the PHP source. On run-time
choose the required language option.
76. What are the difference between abstract class and interface?
Answer: Abstract class: abstract classes are the class where one or more methods are abstract but
not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not defined. The definition of
those methods must be in its extending class.
Interface: Interfaces are one type of class where all the methods are abstract. That means all the
methods only declared but not defined. All the methods must be defined by its implemented class.
77. How can we send mail using JavaScript?
Answer: JavaScript does not have any networking capabilities as it is designed to work on client site.
As a result, we cannot send mails using JavaScript. But we can call the client side mail protocol
mailtovia JavaScript to prompt for an Email to send. this requires the client to approve it.
78. How can we repair a MySQL table?
Answer: The syntax for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ],
[Quick],[Extended].This command will repair the table specified if the quick is given the MySQL will
do a repair of only the index tree if the extended is given it will create index row by row.
15
79. What are the advantages of stored procedures, triggers, indexes?
Answer: A stored procedure is a set of SQL commands that can be compiled and stored in the server.
Once this has been done, clients dont need to keep re-issuing the entire query but can refer to the
stored procedure. This provides better overall performance because the query has to be parsed only
once, and less information needs to be sent between the server and the client. You can also raise
the conceptual level by having libraries of functions in the server. However, stored procedures of
course do increase the load on the database server system, as more of the work is done on the
server side and less on the client (application)side. Triggers will also be implemented. A trigger is
effectively a type of stored procedure, one that is invoked when a particular event occurs. For
example, you can install a stored procedure that is triggered each time a record is deleted from a
transaction table and that stored procedure automatically deletes the corresponding customer from a
customer table when all his transactions are deleted. Indexes are used to find rows with specific
column values quickly. Without an index, MySQL must begin with the first row and then read
through the entire table to find the relevant rows. The larger the table, the more this costs. If the
table has an index for the columns in question, MySQL can quickly determine the position to seek to
in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is
at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster
to read s e q u e n t i a l l y , because this minimizes disk seeks.
80. What is the maximum length of a table name, database name and field name in MySQL?
Answer: The following table describes the maximum length for each type of identifier.
There are some restrictions on the characters that may appear in identifiers.
81. How many values can the SET function of MySQL take?
Answer: MySQL set can take zero or more values but at the maximum it can take 64 values.
82. What are the other commands to know the structure of table using MySQL commands
except explain command?
Answer: describe Table-Name;
83. How many tables will create when we create table, what are they?
Answer: The .frm file stores the table definition. The data file has a .MYD (MYData)
extension. The index file has a .MYI (MYIndex) extension.
84. What is the purpose of the following files having extensions 1) .frm2) .myd
3) .myi? What do these files contain?
Answer: In MySql, the default table type is MyISAM. Each MyISAM table is stored on disk in three
files. The files have names that begin with the table name and have an extension to indicate the file
type.The .frm file stores the table definition. The data file has a .MYD (MYData) extension. The
index file has a .MYI (MYIndex) extension.
16
85. What are the correct and the most two common way to start and finish a PHP block of
code?
Answer: The two most common ways to start and finish a PHP script are: <?php [ PHP
code- ] ?> and <? [ PHP code ] ?>
86. How can we display the output directly to the browser?
Answer: To be able to display the output directly to the browser, we have to use the special tags
<?= and ?>.
87. What is the main difference between PHP 4 and PHP 5?
PHP 5 presents many additional OOP (Object Oriented Programming) features.
88. Is multiple inheritance supported in PHP?
Answer: PHP includes only single inheritance; it means that a class can be extended from only one
single class using the keyword extended.
89. What is the meaning of a final class and a final method?
Answer: final is introduced in PHP5. Final class means that this class cannot be extended and a
final method cannot be overridden.
90. How comparison of objects is done in PHP5?
Answer: 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 referring to the same
instance of the same class by the use of the identity operator ===.
91. How can PHP and HTML interact?
Answer: It is possible to generate HTML through PHP scripts, and it is possible to pass information
from HTML to PHP.
92. What type of operation is needed when passing values through a form or an URL?
Answer: If we would like to pass values through a form or an URL then we need to encode and to
decode them using htmlspecialchars() and urlencode().
93. How can PHP and Javascript interact?
Answer: PHP and Javascript cannot directly interacts since PHP is a server side language and
Javascript is a client side language. However, we can exchange variables since PHP is able to generate
Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP
via the URL.
17
94. What is needed to be able to use image function?
Answer: GD library is needed to be able execute image functions.
95. What is the use of the function imagetypes()?
Answer: imagetypes() gives the image format and types supported by the current version of GD-PHP.
96. What are the functions to be used to get the images properties (size, width and
height)?
Answer: The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
97. How failures in execution are handled with include() and require() functions?
98. Answer: If the function require() cannot access to the file then it ends with a fatal error. However,
the include() function gives a warning and the PHP script continues to execute.
99. What is the main difference between require() and require_once()?
Answer: require() and require_once() perform the same task except that the second function
checks if the PHP script is already included or not before executing it.
(same for include_once() and include())
version when you go in for your interview)
MySQL- 5.5.23
100.
Who is the father of PHP and explain the changes in PHP versions?
Answer: Rasmus Lerdorf is known as the father of PHP.PHP/FI 2.0 is an early and no longer supported
version of PHP. PHP 3 is the successor to PHP/FI 2.0 and is a lot nicer. PHP 4 is the current generation
of PHP, which uses the Zend engine under the hood. PHP 5 uses Zend engine 2 which, among other
things, offers many additional OOPs features.