PHP Interview Questions & Answers
PHP Interview Questions & Answers
PHP
INTERVIEW QUESTIONS
Introduction :
Thanks For Buying This PHP INTERVIEW QUESTIONS Book. This book
is designed to suit the needs of students / professionals who intend to prepare for
interview calls on PHP . Often for the purpose of preparing you to struggle to look
for important topics & browse through some voluble concepts, which you feel
might be asked in an interview. Such a frantic search consumes a lot of time &
energy, as it requires goes through huge volume of PHP Technology. So in order to
solve this dilemma we come up with PHP INTERVIEW QUESTIONS book,
which will equipped to deal with such problems.
Warning : All Rights Reserved . No part of this text or content may be reproduced ,
distributed, including photocopying & other electronic methods are Prohibited.
PHP INTERVIEW QUESTIONS 1
1. What is PHP?
Answers : 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 cretae sites using its CMS.WordPress,osCommerce are the famus CMS of
php.It is also an object oriented programming language like java,C-sharp etc.It is
very eazy for learning
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 type’s data. The $_REQUEST
contains the content of both $_GET, $_POST and $_COOKIE.
Fatal Error – These are basically run time errors which are caused when you try
to access what can’t be done. E.g. accessing a dead object, or trying to use a
function that hasn’t 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 occurs when u try to use a variable that hasn’t been
declared, this will not halt the script, It will give the notice and continue with the
next line of the script.
Answers : 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 ?
Answers : The trim() function removes whitespaces or other predefined characters
from both sides of a string.
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.
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.
Answers :We can include a file using "include() " or "require()" function with file
path as its parameter.
Answers :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.
37. How to create a session? How to set a value in session ? How to Remove data
from a session?
PHP INTERVIEW QUESTIONS 7
38. Is variable name casesensitive ? could we start a variale with number like
$4name ? What is the difference between $name and $$name?
Answers :Yes variable name casesensitive and we can’t 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.
where as $$ is variable of variable $name is variable where as $$name is variable
of variable
like $name=sonia and $$name=singh so $sonia value is singh.
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 ?
Answers :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.
Answers :There are some defference between GET and POST method
1. GET Method have some limit like only 2Kb data able to send for request
PHP INTERVIEW QUESTIONS 8
45. Can we use include (“xyz.PHP”) two times in a PHP page “index.PHP”?
Answers :Yes we can use include(“xyz.php”) more than one time in any page. but
it create a prob when xyz.php file contain some funtions declaration then error
will come for already declared function in this file else not a prob like if you want
to show same content two time in page then must incude it two time not a prob
46. What are the different tables(Engine) present in MySQL, which one is
default?
Answers :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.
PHP INTERVIEW QUESTIONS 9
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)
49. Suppose your Zend engine supports the mode <? ?> Then how can you
configure your PHP Zend engine to support <?PHP ?> mode ?
Answers :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.?
Answers :Nothing more we have to do only redirect to the payPal url after submit
all information needed by paypal like amount,adresss etc.
Answers :Inserts HTML line breaks (<BR />) before all newlines in a string.
54. What are the reasons for selecting lamp (Linux, apache, MySQL, PHP)
instead of combination of other software programs, servers and operating
systems?
Answers :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?
Answers :AES_ENCRYPT () and AES_DECRYPT ()
56. How can we encrypt the username and password using PHP?
Answers :The functions in this section perform encryption and decryption, and
compression and uncompression:
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
$_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
61. How can we take a backup of a MySQL table and how can we restore it. ?
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.
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
PHP INTERVIEW QUESTIONS 12
66. How many ways we can pass the variable through the navigation between the
pages?
Answer : •GET/QueryString
•POST
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.
PHP INTERVIEW QUESTIONS 13
Answer :
Case Studio
Smart Draw
73. How can I retrieve values from one database server and store themin other
database server using PHP?
Answer : WeWe 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 ResultSet, i.e $res1 –
But you cannot execute new query in $db1, even if yousupply 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 failSo 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);
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 moremethods
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.
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.
PHP INTERVIEW QUESTIONS 16
85. What are the correct and the most two common way to start and finish a
PHP block of code?
Answers :The two most common ways to start and finish a PHP script are: <?php
[ — PHP code—- ] ?> and <? [— PHP code —] ?>
92. What type of operation is needed when passing values through a form or an
URL?
Answers :If we would like to pass values througn a form or an URL then we need
to encode and to decode them using htmlspecialchars() and urlencode().
96. What are the functions to be used to get the image’s properties (size, width
and height)?
Answers :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?
Answers :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. 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.
to submit the form without explicitly clicking any submit button. You can attach
the document.formname.submit() method to onclick, onchange events of different
inputs and perform the form submission. you
can even built a timer function where you can automatically submit the form after
xx seconds once the loading is done (can be seen in online test sites).
101. In how many ways we can retrieve the data in the result set of
MySQL using PHP?
Answer : You can do it by 4 Ways
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
104. Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
Answer : Yes we can use include() more than one time in any page though it is not
a very good practice.
106. What is the difference between the functions unlink and unset?
PHP INTERVIEW QUESTIONS 19
Answer : unlink() deletes the given file from the file system.
unset() makes a variable undefined.
108. What is the difference between the functions unlink and unset?
Answer : unlink() deletes the given file from the file system.
unset() makes a variable undefined.
112. List out the top frameworks which are used in PHP?
Answers :1. Laravel
2. CodeIgniter
3. Symfony
2.Phalcon
Answers :exit() function which stops the current php script (Execution of the
page).
We included the
POST function is used when there is a visible change on the state of the world.
When we use a POST function, normally the system changes. E.g. when we add,
delete or modify values from a database. A simple example is a form submission.
117. Is it possible to know details about the browser being used to view a PHP
website?
Ans:Yes. We can use the get_browser() function to get the details of the browser a
user is using. This information is usually found inside the browscap.ini file.
119. How many times is it possible to use an include function in a PHP page?
Ans:We can use include function multiple times in any dynamically generated
PHP page. However, it‟s not considered a good practice to have multiple include
functions on the same page.
PHP INTERVIEW QUESTIONS 21
120. Can you tell me whether objects are passed by value or by reference?
123. What is Full form of PHP ? Who is the father or inventor of PHP ?
Answers :Rasmus Lerdorf is known as the father of PHP that started development
of PHP in 1994
for their own Personal Home Page (PHP) and they released PHP/FI (Forms
Interpreter) version 1.0 publicly on 8 June 1995 But in 1997 two Israeli
developers named Zeev Suraski and Andi Gutmans rewrote the parser that formed
the base of PHP 3 and then changed the language’s name to the PHP: Hypertext
Preprocessor.
124. What are the differences between PHP3 and PHP4 and PHP5 ? what is
the current stable version of PHP ? what advance thing in php6
Answers :The current stable version of PHP is PHP 5.4.5 as still waiting for PHP6
with unicode handlig thing
There are lot of difference among PHP3 and PHP4 and PHP5 version of php so
Difference mean oldest version have less functionality as compare to new one like
1>PHP3 is oldest stable version and it was pure procedural language constructive
like C
2>Where as PHP4 have some OOPs concept added like class and object with new
PHP INTERVIEW QUESTIONS 22
functionality
3>and in PHP5 approximately all major oops functionality has been added along
with below thing
1. Implementation of exceptions and exception handling
2. Type hinting which allows you to force the type of a specific argument
3. Overloading of methods through the __call function
4. Full constructors and destructors etc through a __constuctor and __destructor
function
5. __autoload function for dynamically including certain include files depending
on the class you are trying to create.
6 Finality : can now use the final keyword to indicate that a method cannot be
overridden by a child. You can also declare an entire class as final which prevents
it from having any children at all.
7 Interfaces & Abstract Classes
8 Passed by Reference :
9 An __clone method if you really want to duplicate an object
10 Numbers of Functions Deprecated or removed in PHP 5.x like
ereg,ereg_replace,magic_quotes, session_register,register_globals, split(),
call_user_method() etc
125. Is variable name casesensitive ? could we start a variale with number like
$4name ? What is the difference between $name and $$name?
Answers :Yes variable name casesensitive and we can’t 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.
where as $$ is variable of variable $name is variable where as $$name is variable
of variable
like $name=sonia and $$name=singh so $sonia value is singh.
127. In how many ways we can retrieve the data in the result set of MySQL
PHP INTERVIEW QUESTIONS 23
128. What are the differences between Get and post methods.
Answers :There are some defference 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
132. Can we use include (“xyz.PHP”) two times in a PHP page “index.PHP”?
Answers :Yes we can use include(“xyz.php”) more than one time in any page. but
it create a prob when xyz.php file contain some funtions declaration then error
will come for already declared function in this file else not a prob like if you want
to show same content two time in page then must incude it two time not a prob
PHP INTERVIEW QUESTIONS 24
133. What are the different tables(Engine) present in MySQL, which one is
default?
Answers :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)
Answers :Just run the PHP CLI (Command Line Interface) program and
provide the PHP script file name as the command line argument.
136. Suppose your Zend engine supports the mode <? ?> Then how can you
configure your PHP Zend engine to support <?PHP ?> mode ?
Answers :In php.ini file:
set
short_open_tag=on
to make PHP support
137. Shopping cart online validation i.e. how can we configure Paypal, etc.?
Answers :Nothing more we have to do only redirect to the payPal url after submit
all information needed by paypal like amount,adresss etc
141. What are the reasons for selecting lamp (Linux, apache, MySQL, PHP)
instead of combination of other software programs, servers and operating
systems?
Answers :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.
142. How can we encrypt and decrypt a data present in a MySQL table using
MySQL?
PHP INTERVIEW QUESTIONS 26
144. How is it possible to set an infinite execution time for PHP script?
Answers : 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.
145. What does the PHP error ‘Parse error in PHP – unexpected T_variable at
line x’ means?
Answers : This is a PHP syntax error expressing that a mistake at the line x stops
parsing and executing the program.
151. How is it possible to know the number of rows returned in result set?
Answers : The function mysql_num_rows() returns the number of rows in a result
set.
PHP INTERVIEW QUESTIONS 27
154. How can we access the data sent through the URL with the GET method?
Answers : In order to access the data sent via the GET method, we you use
$_GET array like this:
www.url.com?var=value
$variable = $_GET[“var”]; this will now contain ‘value’
155. How can we access the data sent through the URL with the POST
method?
Answers : To access the data sent this way, you use the $_POST array.
Imagine you have a form field called ‘var’ on the form, when the user clicks
submit to the post form, you can then access the value like this:
$_POST[“var”];
Answers :A static variable is defined within a function only the first time and its
value can be modified during function calls as follows:
returning Arrays.
array_merge gives an array by merging two array ($array1, $array2) and both can
have different number of elements. $array1 and $array2 are added in returning
array.
173. What is Difference between local variable and data members or instance
variable?
Answer: 1. A data member belongs to an object of a class whereas local variable
belongs to its current scope.
2. A local variable is declared within the body of a function and can be used only
from the point at which it is declared to the immediately following closing brace.
PHP INTERVIEW QUESTIONS 30
3. Data members are accessible to all member function of the class. Local variable
are not accessible in any another function or class.
2. The only rule is that static methods or properties are out of object context.
3. Public function of class can be access by scope resolution operator (i.e ::)
and Object Reference Operator (i.e ->) but public data member can't be
access through scope resolution operator.
Disadvantages
Refactoring is harder. Renaming or changing where the store proc is might
produce a bad effect.
Unit testing stored proc require code assistance outside the DB
The number(eg 1,2,3,4,5....) that follows the "WWW" indicates that the data being
retrieved by the Web browser is gathering the information from a different Web
server than the one that serves the typical "WWW" address.
Web sites, especially dynamic Web sites, that handle large amounts of traffic often
need more than one server to accommodate the many requests they receive as one
server often cannot handle the multitude of requests.
Examples
https://www1.pearsonvue.com/
https://www2.pearsonvue.com/
https://www3.pearsonvue.com/
https://www4.pearsonvue.com/
https://www5.pearsonvue.com/
https://www6.pearsonvue.com/
Here all above websites have same data.
Purpose: Analyse the performance, user satisfaction & expectation then Convert
into percentage.
Formula
Apdex = (Satisfied + Tolerating / 2) / Total
PHP INTERVIEW QUESTIONS 34
Example: https://docs.newrelic.com/docs/assets/apdex.pdf
194. How we can retrieve the data in the result set of MySQL using PHP?
Answers :1. mysql_fetch_row
2. mysql_fetch_array
3. mysql_fetch_object
PHP INTERVIEW QUESTIONS 36
4. mysql_fetch_assoc
198. Write down the code for save an uploaded file in php.
Answers : if ($_FILES["file"]["error"] == 0)
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
200. How to strip whitespace (or other characters) from the beginning and end
of a string ?
Answers :
The trim() function removes whitespaces or other predefined characters from both
sides of a string.
Answers : 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);
immediate termination of the script, and PHP's default behavior is to display them
to the user when they take place.
These errors are non-critical and trivial errors that come across while executing
the script in PHP. Example: trying to gain access the variable which is not
defined. These errors are not showed to the users by default even if the default
behavior is changed.
Fatal errors:
These are critical errors. Example: instantiating an object of a class which does
not exist or a non-existent function is called. These errors results in termination of
the script immediately and default behavior of PHP is shown to them when they
take place. Twelve different error types are used to represent these variations
internally.
233. What are the differences between Get and post methods in form
submitting. Give the case where we can use get and we can use post methods?
Answer : When to use GET or POST
The HTML 2.0 specification says, in section Form Submission (and the HTML
4.0 specification repeats this with minor stylistic changes):
–>If the processing of a form is idempotent (i.e. it has no lasting observable effect
on the state of the
world), then the form method should be GET. Many database searches have no
visible side-effects and make ideal applications of query forms.
–
–>If the service associated with the processing of a form has side effects (for
example, modification of a database or subscription to a service), the method
should be POST.
that whereas one GET request might (rarely) change some state on the Server, two
or more identical requests will have no further effect.
This is a theoretical point which is also good advice in practice. If a user hits
“reload” on his/her browser, an identical request will be sent to the server,
potentially resulting in two identical database or guestbook entries, counter
increments, etc. Browsers may reload a GET URL automatically, particularly if
cacheing is disabled (as is usually the case with CGI output), but will typically
prompt the user before re-submitting a POST request. This means you’re far less
likely to get inadvertently-repeated entries from POST.
GET is (in theory) the preferred method for idempotent operations, such as
querying a database, though it matters little if you’re using a form. There is a
further practical constraint that many systems have built-in limits to the length of
a GET request they can handle: when the total size of a request (URL+params)
approaches or exceeds 1Kb, you are well-advised to use POST in any
case.
I would prefer POST when I don’t want the status to be change when user
resubmits. And GET
when it does not matter.
236. 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.
238. In how many ways we can retrieve the data in the result set of
MySQL using PHP?
PHP INTERVIEW QUESTIONS 44
1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
$message = “Raghav”;
$$message = “is a owner of https://sharag.wordpress.com/ “;
$message is a simple PHP variable that we are used to. But the $$message is not a
very familiar face. It creates a variable name $mizan with the value “is a
moderator of PHPXperts.” assigned. break it like this${$message} =>
$mizanSometimes it is convenient to be able to have variable variable names.
That is, a variable name which can be set and used dynamically.
Answer : preg_match(”/^http://.+@(.+)$/”,’[email protected]’,$found);
echo $found[1];
243. What are the differences between require and include, include_once and
PHP INTERVIEW QUESTIONS 45
require_once?
Answer :
The include() statement includes and evaluates the specified file.The
documentation below also applies to require(). The two constructs are identical in
every way except how they handle
failure. include() produces a Warning while require() results in a Fatal Error. In
other words, use
require() if you want a missing file to halt processing of the page. include() does
not behave this way, the script will continue regardless. The include_once()
statement includes and evaluates the
specified file during the execution of the script. This is a behavior similar to the
include() statement, with the only difference being that if the code from a file has
already been included, it will not be
included again. As the name suggests, it will be included just once.include_once()
should be used in cases where the same file might be included and evaluated more
than once during a particular execution of a script, and you want to be sure that it
is included exactly once to avoid problems with function redefinitions, variable
value reassignments, etc. require_once() should be used in cases where the same
file might be included and evaluated more than once during a particular execution
of a script, and you want to be sure that it is included exactly once to avoid
problems with function
redefinitions, variable value reassignments, etc
244. Can we use include (”abc.PHP”) two times in a PHP page “makeit.PHP”?
Answer : Yes we can use include() more than one time in any page though it is
not a very good practice.
245. What are the different tables present in MySQL, which type of table is
generated when we are creating a table in the following syntax:
create table employee (eno int(2),ename varchar(10)) ?
default engine.
248. 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
249. Shopping cart online validation i.e. how can we configure Paypal,
etc.?
Answer : We can find the detail documentation about different paypal integration
process at the following site PayPal PHP
SDK : http://www.paypaldev.org/
PHP script was loaded by the Zend Engine and compiled into Zend opcode.
Opcodes, short for operation codes, are low level binary instructions. Then
the opcode was executed and the HTML generated sent to the client. The
opcode was flushed from memory afterexecution.Today, there are a multitude
of products and techniques to help you speed up this process. In the following
diagram, we show the how modern PHP scripts work; all the shaded boxes
are optional.
PHP Scripts are loaded into memory and compiled into Zend opcodes.
252. What are the current versions of apache, PHP, and MySQL?
Answer : As of Aug 2008 the current versions are PHP: php5.2.6
MySQL: MySQL 5.1.2
Apache: Apache 2.2.9
Note: visit
http://www.php.net/,
http://dev.mysql.com/downloads/mysql/,
http://www.apache.org/ to get current
versions.
PHP INTERVIEW QUESTIONS 48
253. 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.
254. How can we encrypt and decrypt a data present in a MySQL table using
MySQL?
Answer : AES_ENCRYPT () and AES_DECRYPT ()
255. How can we encrypt the username and password using PHP?
Answer : The functions in this section perform encryption and decryption, and
compression and uncompression:
they do not result in script termination.3. Fatal errors: These are critical errors –
for example,
instantiating an object of a non-existent class, or calling a non-existent function.
These errors cause the immediate termination of the script, and PHP’s default
behavior is to display them to the user when they take place.
262. What are the differences between PHP 3 and PHP 4 and PHP 5?
Answer : PHP 3 is most procedure oriented and , PHP4 and PHP5 aer object
oriented. For more details
http://php.net/
265. How can we get second of the current time using date function?
Answer : $second = date(”s”);
268. What is the difference between the functions unlink and unset?
Answer : unlink() deletes the given file from the file system.
unset() makes a variable undefine
that can be created from several files. This allows a table to exceed the maximum
individual file size. The table space can include raw disk partitions, which allows
extremely large tables. The maximum table space size is 64TB.The following
table lists some examples of operating system file-size limits. This is only a rough
guide and is not intended to be definitive.For the most up-to-date information, be
sure to check the documentationspecific to your operating system.Operating
System File-size Limit Linux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
(making the field atomic). Second Normal Form Where the First Normal Form
deals with redundancy of data across a horizontal row, Second Normal Form (or
2NF) deals with redundancy of data in vertical columns. As stated earlier, the
normal forms are progressive, so to achieve Second Normal Form, your tables
must already be in First NormalForm.Third Normal Form I have a confession to
make; I do not often use Third Normal Form. In Third Normal Form we are
looking for data in our tables that is not fully dependent on the primary key, but
dependent on another value in the table.
273. How can we find the number of rows in a table using MySQL?
Answer : Use this for mysql>SELECT COUNT(*) FROM table_name;
274. How can we find the number of rows in a result set using PHP?
Answer :
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;
275. How many ways we can we find the current date using MySQL?
Answer :
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use SELECT CURTIME();
CURRENT_TIME() = CURTIME()
276. What are the advantages and disadvantages of Cascading Style Sheets?
Answer :
External Style Sheets
Advantages : Can control styles for multiple documents at once. Classes can be
created for use on multiple HTML element types in many documents.Selector and
grouping methods can be used to apply styles under complex contexts.
Disadvantages : An extra download is required to import style information for
eachdocument The rendering of the document may be delayed until the
externalstyle sheet is loaded becomes slightly unwieldy for small quantities
ofstyle definitions.
Embedded Style Sheets
Advantages : Classes can be created for use on multiple tag types in the
document.Selector and grouping methods can be used to apply styles under
complexcontexts. No additional downloads necessary to receive style information.
PHP INTERVIEW QUESTIONS 55
Disadvantages : This method can not control styles for multiple documents at
once.
Inline Styles
Advantages : Useful for small quantities of style definitions. Can override
otherstyle specification methods at the local level so only exceptions needto be
listed in conjunction with other style methods.
Disadvantages : Does not distance style information from content (a main goal
ofSGML/HTML). Can not control styles for multiple documents at once.Author
can not create or control classes of elements to control multipleelement types
within the document. Selector grouping methods can not beused to create
complex element addressing scenarios
278. What is the difference between Primary Key and Unique key
Answers : Primary Key: A column in a table whose values uniquely identify
therows in the table. A primary key value cannot be NULL. Unique Key: Unique
Keys are used to uniquely identify each row in thetable. There can be one and
only one row for each unique key value. So NULL can be a unique key.There can
be only one primary key for a table but there can be morethan one unique for a
table
the value of user_pri_id the last row 999 then What will happen inthe
following conditions?Condition1: Delete all the rows and insert another row
PHP INTERVIEW QUESTIONS 56
then.What is the starting value for this auto incremented field user_pri_id
,Condition2: Delete the last row(having the field value 999) andinsert another
row then. What is the value for this auto incremented field user_pri_id.
Answer : In both cases let the value for auto increment field be n then nextrow
will have value n+1 i.e. 1000.
282. What is the difference between char and varchar data types?
Answer : Set char to occupy n bytes and it will take n bytes even if u r storing a
value of n-m bytes Set varchar to occupy n bytes and it will take only the required
space and will not use the n bytes eg. name char(15) will waste 10 bytes if we
store ‘mizan’, if each char takes a byte eg. name varchar(15) will just use 5 bytes
if we store ‘mizan’, if each char takes a byte. rest 10 bytes will be free.
284. How can I load data from a text file into a table?
Answer : you can use LOAD DATA INFILE file_name; syntax to load datafrom a
text file. but you have to make sure thata) data is delimitedb) columns and data
matched correctly.
285. How can we know the number of days between two given dates using
PHP INTERVIEW QUESTIONS 57
MySQL?
Answer : SELECT DATEDIFF(’2007-03-07?,’2005-01-01?);
286. How can we know the number of days between two given dates using
PHP?
Answer : $date1 = date(’Y-m-d’);
$date2 = ‘2006-08-15?;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
287. How can we encrypt the username and password using PHP?
The functions in this section perform encryption and decryption, and
compression and uncompression:
291. What are the differences between public, private, protected, static,
transient, final and volatile?
Answers : Public: Public declared items can be accessed everywhere.
Protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
Private: Private limits visibility only to the class that defines
the item.
Static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
Final: Final keyword prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
PHP INTERVIEW QUESTIONS 59
297. How can we get second of the current time using date function?
Answers : $second = date(“s”);
300. What is the difference between the functions unlink and unset?
Answers : unlink() deletes the given file from the file system.
unset() makes a variable undefined.
302. How can we get the properties (size, type, width, height) of an image using
PHP image functions?
Answers : 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 t
Answers : “13” and 12 can be compared in PHP since it casts everything to the
integer type.
315. If the variable $var1 is set to 10 and the $var2 is set to the character var1,
what’s the value of $$var2?
Answers : $$var2 contains the value 10.
Or
2- $variable3 = “$variable1$variable2”;
$variable3 will contain “Hello World”. The first code is faster than the second
code especially for large large sets of data.
331. How can we get the error when there is a problem to upload a file?
Answers : $_FILES[‘userfile’][‘error’] contains the error code associated with the
uploaded file.
332. How can we change the maximum size of the files to be uploaded?
Answers : We can change the maximum size of files to be uploaded by changing
upload_max_filesize in php.ini.
336. what the difference between the ‘BITWISE AND’ operator and the
‘LOGICAL AND’ operator?
Answers : $a and $b: TRUE if both $a and $b are TRUE.
$a & $b: Bits that are set in both $a and $b are set.
Exception::getLine ?
Answers : Exception::getMessage lets us getting the Exception message and
Exception::getLine lets us getting the line in which the exception occurred.
346. What is the difference between the functions strstr() and stristr()?
Answers : The string function strstr(string allString, string occ) returns part of
allString from the first occurrence of occ to the end of allString. This function is
case-sensitive. stristr() is identical to strstr() except that it is case insensitive.
The first expression is executed once at the beginning. In each iteration, expr2 is
evaluated. If it is TRUE, the loop continues and the statements inside for are
executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested
at the end of each iteration.
However, foreach provides an easy way to iterate over arrays and it is only used
with arrays and objects.
351. What are the three classes of errors that can occur in PHP?
Answers : The three basic classes of errors are notices (non-critical), warnings
(serious errors) and fatal errors (critical errors).
353. How can we pass the variable through the navigation between the pages?
Answers : It is possible to pass the variables between the PHP pages using
sessions, cookies or hidden form fields.
358. What function do we use to find length of string, and length of array?
Answers : For finding length of string we use strlen() function and for array we
use count() function.
372. What is JOIN in mysql? What are the different types of join?
Answers : When we have to fetch records from more than one table we can use
JOIN keyword. The process is known as joining the tables. There are various
types of join like INNER JOIN, LEFT JOIN, RIGHT JOIN, and OUTER JOIN.
373. Why is the basic difference between LEFT JOIN, RIGHT JOIN and
INNER JOIN?
Answers :
INNER Join compares two tables and only returns results where a match exists.
Records from the 1st table are duplicated when they match multiple results in the
2nd. INNER joins tend to make result sets smaller, but because records can be
duplicated this isn’t guaranteed.
LEFT join means keep all records from the 1st table no matter what and insert
NULL values when the 2nd table doesn’t match.
RIGHT Join means the opposite: keep all records from the 2nd table no matter
what and insert NULL values when the 1st table doesn’t match.
PHP INTERVIEW QUESTIONS 70
374. If we use SUM function in mysql, does it return sum of that row or for
that column?
Answers :
Sum function works on the column basis and will return the sum of that particular
row only.
Another case is where you need to fetch all customer data where kumar is found
irrespective of the position (middle name or last name).
In this case it will delete the record of the customer with customer id 150
like $6name as a valid variable name starts with a letter or underscore, followed
by any number of letters, numbers, or underscores.
array_combine example
$array1 = array('one','two');
$array2 = array(1,2);
$result = array_combine($array1,$array2);
print_r($result);
While PDO has its advantages, such as a clean, simple, portable API but its
maindisadvantage is that it doesn’t allow you to use all of the advanced features that
are available in the latest versions of MySQL server. For example, PDO does not
allow you to use MySQL’s support for Multiple Statements.
Just need to use below code for connect mysql using PDO
try {
$dbh = new PDO(“mysql:host=$hostname;dbname=databasename”, $username,
$password);
$sql = “SELECT * FROM employee”;
foreach ($dbh->query($sql) as $row)
{
print $row['employee_name'] .’ – ‘. $row['employee_age'] ;
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
A web site, mailing lists and download mirrors to support the PHP/PEAR
communityPEAR is a community-driven project with the PEAR Group as the
governing body. The project has been founded by Stig S. Bakken in 1999 and quite a
lot of people have joined the project since then.
423. How can we know the number of days between two given dates using
PHP?
Simple arithmetic:
$date1 = date(‘Y-m-d’);
$date2 = ’2006-07-01′;
$days = (strtotime() – strtotime()) / (60 * 60 * 24);
echo “Number of days since ’2006-07-01′: $days”;
PHP INTERVIEW QUESTIONS 80
427. What does a special set of tags <?= and ?> do in PHP?
The output is displayed directly to the browser.
428. How do you define a constant?
Via define() directive, like define (“MYCONSTANT”, 100);
429. What are the differences between require and include, include_once?
PHP INTERVIEW QUESTIONS 81
require_once() and include_once() are both the functions to include and evaluate the
specified file only once. If the specified file is included previous to the present call
occurrence, it will not be done again.But require() and include() will do it as many
times they are asked to do.
The include_once() statement includes and evaluates the specified file during the
execution of the script. This is a behavior similar to the include() statement, with the
only difference being that if the code from a file has already been included, it will
not be included again. The major difference between include() and require() is that in
failure include() produces a warning message whereas require() produces a fatal
errors.
431. How To Get the Uploaded File Information in the Receiving Script?
Once the Web server received the uploaded file, it will call the PHP script specified
in the form action attribute to process them. This receiving PHP script can get the
uploaded file information through the predefined array called $_FILES. Uploaded
file information is organized in $_FILES as a two-dimensional array as:
$_FILES[$fieldName]['name'] – The Original file name on the browser system.
$_FILES[$fieldName]['type'] – The file type determined by the browser.
$_FILES[$fieldName]['size'] – The Number of bytes of the file content.
PHP INTERVIEW QUESTIONS 82
434. How can we optimize or increase the speed of a MySQL select query?
• 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.
435. How many ways can we get the value of current session id?
session_id() returns the session id for the current session.
436. How can we destroy the session, how can we unset the variable of a
session?
session_unregister – Unregister a global variable from the current session
session_unset – Free all session variables
438. How many ways we can pass the variable through the navigation
between the pages?
• GET/QueryString
• POST
443. How can I know that a variable is a number or not using a JavaScript?
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.
444. List out some tools through which we can draw E-R diagrams for mysql.
Case Studio
Smart Draw
445 . How can I retrieve values from one database server and store them in
PHP INTERVIEW QUESTIONS 84
447 . How can I make a script that can be bi-language (supports English,
German)?
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 runtime choose the required language option.
448 . What are the difference between abstract class and interface?
Abstract class: abstract classes are the class where one or more methods are abstract
PHP INTERVIEW QUESTIONS 85
452. What is the maximum length of a table name, database name, and
fieldname in MySQL?
The following table describes the maximum length for each type of identifier.
Identifier Maximum Length
(bytes)
Database 64
Table 64
Column 64
Index 64
Alias 255
There are some restrictions on the characters that may appear in identifiers.
453. How many values can the SET function of MySQL take?
MySQL set can take zero or more values but at the maximum it can take 64 values
454. What are the other commands to know the structure of table using
MySQL commands except explain command?
describe Table-Name;
455. How many tables will create when we create table, what are they?
The ‘.frm’ file stores the table definition.
The data file has a ‘.MYD’ (MYData) extension.
The index file has a ‘.MYI’ (MYIndex) extension,
456. What is the purpose of the following files having extensions 1) .frm 2)
.myd 3) .myi? What do these files contain?
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,
number of tables in a database. If the time required to open a file in the directory
increases significantly as the number of files increases, database performance can be
adversely affected.
The amount of available disk space limits the number of tables.
MySQL 3.22 had a 4GB (4 gigabyte) limit on table size. With the MyISAM storage
engine in MySQL 3.23, the maximum table size was increased to 65536 terabytes
(2567 1 bytes). With this larger allowed table size, the maximum effective table size
for MySQL databases is usually determined by operating system constraints on file
sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB
tables within a tablespace that can be created from several files. This allows a table
to exceed the maximum individual file size. The tablespace can include raw disk
partitions, which allows extremely large tables. The maximum tablespace size is
64TB.
The following table lists some examples of operating system file-size limits. This is
only a rough guide and is not intended to be definitive.For the most up-to-date
information, be sure to check the documentation specific to your operating system.
Operating System File-size LimitLinux 2.2-Intel 32-bit 2GB (LFS: 4GB)
Linux 2.4+ (using ext3 filesystem) 4TB
Solaris 9/10 16TB
NetWare w/NSS filesystem 8TB
Win32 w/ FAT/FAT32 2GB/4GB
Win32 w/ NTFS 2TB (possibly larger)
MacOS X w/ HFS+ 2TB
460. How can we find the number of rows in a table using MySQL?
Use this for mysql
>SELECT COUNT(*) FROM table_name;
461. How can we find the number of rows in a result set using PHP?
$result = mysql_query($sql, $db_link);
$num_rows = mysql_num_rows($result);
echo “$num_rows rows found”;
462. How many ways we can we find the current date using MySQL?
SELECT CURDATE();
CURRENT_DATE() = CURDATE()
for time use
SELECT CURTIME();
CURRENT_TIME() = CURTIME()
PHP INTERVIEW QUESTIONS 89
463. What are the advantages and disadvantages of Cascading Style Sheets?
External Style SheetsAdvantagesCan control styles for multiple documents at once.
Classes can be created for use on multiple HTML element types in many documents.
Selector and grouping methods can be used to apply styles under complex
contextsDisadvantagesAn extra download is required to import style information for
each document The rendering of the document may be delayed until the external
style sheet is loaded Becomes slightly unwieldy for small quantities of style
definitions Embedded Style Sheets
Advantages
Classes can be created for use on multiple tag types in the document.
Selector and grouping methods can be used to apply styles under complex contexts.
No additional downloads necessary to receive style information
Disadvantages
This method can not control styles for multiple documents at once Inline Styles
Advantages
Useful for small quantities of style definitions. Can override other style specification
methods at the local level so only exceptions need to be listed in conjunction with
other style methods
Disadvantages
Does not distance style information from content (a main goal of SGML/HTML).
Can not control styles for multiple documents at once.
Author can not create or control classes of elements to control multiple element
types within the document. Selector grouping methods can not be used to create
complex element addressing scenarios
465. What is the difference between Primary Key and Unique key?
Primary Key: A column in a table whose values uniquely identify the rows in the
table. A primary key value cannot be NULL.
Unique Key: Unique Keys are used to uniquely identify each row in the table. There
can be one and only one row for each unique key value. So NULL can be a unique
key.There can be only one primary key for a table but there can be more than one
unique for a table.
469. What is the difference between char and varchar data types?
Set char to occupy n bytes and it will take n bytes even if u r storing a value of n-m
bytes
Set varchar to occupy n bytes and it will take only the required space and will not
use the n bytes
eg. name char(15) will waste 10 bytes if we store ‘romharshan’, if each char takes a
byte
eg. name varchar(15) will just use 5 bytes if we store ‘romharshan’, if each char
takes a byte. rest 10 bytes will be free.
471. How can I load data from a text file into a table?
you can use LOAD DATA INFILE file_name; syntax to load data from a text file.
but you have to make sure that
a) data is delimited
b) columns and data matched correctly
472. How can we know the number of days between two given dates using
MySQL?
SELECT DATEDIFF(“2007-03-07″,”2005-01-01″);
473. How can we know the number of days between two given dates using PHP?
$date1 = date(“Y-m-d”);
$date2 = “2006-08-15″;
$days = (strtotime($date1) – strtotime($date2)) / (60 * 60 * 24);
476. What is the difference between the functions unlink and unset?
unlink: delete the files from Server.
unset: delete the variable name and data from memory.
PHP INTERVIEW QUESTIONS 92
478. What are the various methods to pass data from one web page to another
web page?
Session
Cookie
Database
URL parameters
482.What is CMS?
CMS means Content Management System. It is web software who provide the
website full fledgedcontent management where owner can add/update/delete the
html/files/images/videos etc. Today's CMS do much more as compare to its
name.
For example. Joomla/Wordpress is CMS but you can create E-commererce
website and can accpet all types of payment.
In Today's CMS, you can create many different types of website like
Ecommerce website, Personal blogging and Forum etc.
WWW ability to recognize and handle files of different types is largely dependent on
the use of the MIME (Multipurpose Internet Mail Extensions) standard. The standard
provides for a system of registration of file types with information about the
applications needed to process them.
Outco
Compared URL me Reason
httpː//www.example.com/dir/pa Succe Same protocol and host
PHP INTERVIEW QUESTIONS 95
ge2.html ss
httpː//www.example.com/dir2/o Succe
ther.html ss Same protocol and host
httpː//www.example.com:81/dir/ Failur
other.html e Same protocol and host but different port
https://www.example.com/dir/ot Failur
her.html e Different protocol
http://en.example.com/dir/other. Failur
html e Different host
http://example.com/dir/other.ht Failur
ml e Different host (exact match required)
http://v2.www.example.com/dir/ Failur
other.html e Different host (exact match required)
httpː//www.example.com:80/dir/ Don't Port explicit. Depends on implementation
other.html use in browser.
492. How can PHP read the hash portion of the URL?
Answer: PHP can't read the hash portion of the URL
index.php?page=group#birthday
Here, PHP can not read the birthday
493. What are static method? How its different from normal method?
Answer: 1. Static methods are that can be accessed by using the scope resolution
operator (i.e ::) and object reference operator ( i.e.-> ).
MyClass::mystatic();
$obj->mystatic();
495. How to import database from desktop to server with use of command line?
1) Make a zip of sql dump file and upload the zip file to server through FTP.
PHP INTERVIEW QUESTIONS 97
2) Login to Putty/Console
3) Go the directory with use of cd command, the location where you have upload the
zip file.
4) unizip that zip file, with following command
unzip zipfilename.zip
3)Import the sql dump file with use of following command.
mysql -u username -p databasename < sqlfilename.sql
497. How to export database to sql file with use of command line?
1) Login to Putty/Console
2) Execute following commands to export the sql dump into server.
mysqldump –u username –p databasename tablename > sqlfilename.sql
(It will prompt password)
500. How can we take a backup of a MySQL table and how can we restore it. ?
To backup: BACKUP TABLE tbl_name[,tbl_name ¦] TO
‘/path/to/backup/directory’
RESTORE TABLE tbl_name[,tbl_name ¦] FROM
‘/path/to/backup/directory’mysqldump: 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
Don’t write table creation information (the CREATE TABLE statement).
-d, “no-data
Don’t 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!
encryption decryption
AES_ENCRYT() AES_DECRYPT()
ENCODE() DECODE()
DES_ENCRYPT() DES_DECRYPT()
ENCRYPT() Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD() Not available
SHA() or SHA1() Not available
Not available UNCOMPRESSED_LENGTH()
501. How we load all classes that placed in different directory in one PHP File ,
means how to do auto load classes
by using spl_autoload_register(‘autoloader::funtion’);
Like below
class autoloader
{
{
$path = $_SERVER['DOCUMENT_ROOT'] . “/modules/{$class}.php”;
if (is_readable($path)) require $path;
}
502. How many types of Inheritances used in PHP and how we achieve it
As far PHP concern it only support single Inheritance in scripting.
we can also use interface to achieve multiple inheritance.
505. how to track user logged out or not? when user is idle ?
By checking the session variable exist or not while loading th page. As the session will
exist longer as till browser closes. The default behaviour for sessions is to keep a session
open indefinitely and only to expire a session when the browser is closed. This
behaviour can be changed in the php.ini file by altering the line session.cookie_lifetime
= 0 to a value in seconds. If you wanted the session to finish in 5 minutes you would set
this to session.cookie_lifetime = 300 and restart your httpd server.
510. I am trying to assign a variable the value of 0123, but it keeps coming up with
a different number, what’s the problem?
PHP INTERVIEW QUESTIONS 101
PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP
interview questions for more numeric problems.
511. Would I use print “$a dollars” or “{$a} dollars” to print out the amount of
dollars in this example?
In this example it wouldn’t matter, since the variable is all by itself, but if you were to
print something like “{$a},000,000 mln dollars”, then you definitely need to use the
braces.
512. What are the different tables present in MySQL? Which type of table is
generated when we are creating a table in the following syntax: create table
employee(eno int(2),ename varchar(10))?
Total 5 types of tables we can create
1. MyISAM2. Heap
3. Merge
4. INNO DB
5. ISAM
MyISAM is the default storage engine as of MySQL 3.23. When you fire the above
create query MySQL will create a MyISAM table.
514. How can we encrypt the username and password using PHP?
You can encrypt a password with the following Mysql>SET
PASSWORD=PASSWORD(“Password”);
You can also use the MySQL PASSWORD() function to encrypt username and
password. For example,
INSERT into user (password, …) VALUES (PASSWORD($password”)), …);
516. When are you supposed to use endif to end the conditional statement?
When the original if was followed by : and then the code block without braces.
PHP INTERVIEW QUESTIONS 102
520. How do I find out the number of parameters passed into function. ?
func_num_args() function returns the number of parameters passed in.
521. What is the purpose of the following files having extensions: frm, myd, and
myi? What these files contain?
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,
MIME types represents a standard way of classifying file types over Internet.
PHP INTERVIEW QUESTIONS 103
Web servers and browsers have a list of MIME types, which facilitates files transfer of
the same type in the same way, irrespective of operating system they are working in.
A MIME type has two parts: a type and a subtype. They are separated by a slash (/).
MIME type for Microsoft Word files is application and the subtype is msword, i.e.
application/msword.Explain how to execute a PHP script using command line.
PHP script using command line can be executed using SAPI (Server Application
programming Interface). Using SAPI Command Line Interface the PHP code can be
passed to execute directly
253. How can we increase the execution time of a PHP script?
By default the PHP script takes 30secs to execute. This time is set in the php.ini file.
This time can be increased by modifying the max_execution_time in seconds. The time
must be changed keeping the environment of the server. This is because modifying the
execution time will affect all the sites hosted by the server.Explain the purpose of output
buffering in PHP.
Output buffering in PHP buffers a scripts output. This buffer can be edited before
returning it to the client. Without output buffering, PHP sends data to the web server as
soon as it is ready. Output buffering "send" cookies at any point in the script. Cookies do
not have to be necessarily sent near the start of page. Output buffers are stackable and
hence sending to output is by choice.How can we know the number of days between two
given dates using PHP?
The start date and end date can be first found as shown below:
$date1= strotime($start_date);
$date2= strotime($end_date);
$date_diff = (($date1)- ($date2)) / (60*60*24)Write the statements that are used to
connect PHP with MySQL
The statements that can be used to connect PHP wil MySQL is:
<?
$conn = mysql_connect('localhost');
echo $conn;
?>
This statement gets the resource of the localhost. There are other different ways with
which you can connect to the database and they are as follows:
<?
mysql_connect('db.domain.com:33306','root','user');
mysql_connect('localhost:/tmp/mysql.sock');
mysql_connect('localhost','rasmus','foobar',
PHP INTERVIEW QUESTIONS 104
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')?>
524. Why many companies are switching their current business language to PHP?
Where PHP basically used?
PHP is rapidly gaining the popularity and many companies are switching their current
language for this language. PHP is a server side scripting language. PHP executes the
instructions on the server itself. Server is a computer where the web site is located. PHP
is used to create dynamic pages and provides faster execution of the instructions.Why
PHP is sometimes called as embedded scripting language?
PHP is a high level language which is used to allow users to write and understand it in
human readable form and also use an interpreter to interpret the code which user write
for the computer. PHP is used as an embedded scripting language for the web. PHP is
embedded in HTML code. HTML tags are used to enclose the PHP language. HTML is
used and PHP is code written in it in the same way as you write JavaScript in HTML.
What is difference between require_once(), require(), include()?
require() includes and evaluates a specific file, if the file is not found then it shows a
Fatal Error.
require_once() includes only the file which is not being included before. It is used to be
recommended for the files where you have lots of functions stored.
include() includes the file, even if the file is not found, but it gives a warning to the user
to include().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.
print(“</html>”);
?>
528. Are objects passed by value or by reference?
Everything is passed by value.
535. How many ways we can pass the variable through the navigation between the
pages?
Register the variable into the session
Pass the variable as a cookie
Pass the variable as part of the URL
CRYPT(), MD5()
544. What are the differences between Get and post methods.
PHP INTERVIEW QUESTIONS 109
549. How can we encrypt the username and password using php?
You can encrypt a password with the following Mysql>SET
PASSWORD=PASSWORD("Password");
We can encode data using base64_encode($string) and can decode using
base64_decode($string);
PHP INTERVIEW QUESTIONS 110