Php Interview Questions

  • Question: How can I load data from a text file into a table?

The mysql provides  a LOAD DATA INFILE syntax. However you need to make sure that:
a) Data is delimited
b) You match the columns and data correctly

  • Question: What is meant by urlencode and urldecode?

string urlencode(str)

  • where str contains a string for example �hello world� and the return value will be URL encoded and can be use to append with URLs‚ normaly used to appned data for GET like string urldocode(str) this will simply decode the GET variable�s

value for example echo (urldecode($_GET_VARS[var])) will output �Hello world�

  • Question: What are different names of PHP?

Personal Homepage and PHP: Hypertext Preprocessor

  • Question: What is Scripts and Files?

A script may include many files‚ this enables PHP coders to write some of the code once‚ and use it in many scripts‚ to include an external file into your script‚ you can use one of the following:
1. include: reads the external file‚ and interprets it‚ if the external file can't be found‚ a warning is produced‚ and the execution continues.
2. require: the same as includes‚ but it causes the execution to stop.
3. include_once: works the same way as include‚ but the included file will be interpreted just once‚ at the first time it's included‚ if it's included again in the same file‚ it won't be interpreted again.
4. require_once: the same as require‚ but also interpreted once like include_once.

  • Question: What are the differences between Get and post methods in form submitting?

Answer: In the get method the data made available to the action page (where data is received) by the URL so data can be seen in the address bar. Not advisable if you are sending login info like password etc. In the post method the data will be available as data blocks and not as query string in case of get method.The key difference between GET and POST is that POST has side-
effects‚ and thus browsers will present a confirmation dialog to the user on refresh or "back".

  • Question: What is the difference between characters 23 and x23?

The first one is octal 23, the second is hex 23.

  • Question: I want to combine two variables together:

1. $var1 = 'Welcome to ';
2. $var2 = '';

  • Question: What will work faster?

Code sample 1:$var 3 = $var1.$var2;Or code sample 2:$var3 = "$var1$var2";
Both examples would provide the same result - $var3 equal to "Welcome to". However, Code Sample 1 will work significantly faster. Try it out with large sets of data (or via concatenating small sets a million times or so), and you will see that concatenation works significantly faster than variable substitution.

  • Question: For printing out strings, there are echo, print and printf. Explain the differences.

Echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like: and it will output the string "Welcome to TechInterviews!" print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf  is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

  • Question:.What’s the difference between htmlentities() and htmlspecialchars()? htmlspecialchars only takes care of , single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.
  • Question: meaning of hypertext preprocessor

Preprocessor defines the process which takes place in server side and returns the plain html form to the web browser...Hypertext nothing but the plain web page

  • Question: what is DDL‚ DML and DCL?

Data Definition Language (DDL) is a computer language for defining data structures. Like the SQL CREATE statements‚ DROP statements‚ ALTER statements
Data Manipulation Language (DML) - is a family of computer languages used by computer programs or database users to retrieve‚ insert‚ delete and update data in a database
Data Control Language (DCL) - is a computer language and a subset of SQL‚ used to control access to data in a database
Examples of DCL commands include:
* GRANT to allow specified users to perform specified tasks.
* REVOKE to cancel previously granted or denied permissions.

  • Question: Who is the father of php?

Rasmus Lerdorf

  • Question: What does a special set of tags do in PHP?

The output is displayed directly to the browser.

  • Question: What’s the difference between include and require?

It’s how they handle failures. 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.

  • Question: How do you pass a variable by value?

Just like in C++, put an ampersand in front of it, like $a = &$b

  • Question: 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.

  • Question: What is the difference between $name and $$name?

$name is variable where as $$name is reference variable like $name=sonia and $$name=singh so $sonia value is singh.

  • Question:.How can we submit a form without a submit button?

Java script submit() function is used for submit form without submit buttonon click call document.formname.submit()

  • Question: In how many ways we can retrieve the data in the result set of MySQL using PHP?

We can do it by 4 Ways

mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object 4. mysql_fetch_assoc

  • Question: What is the difference between mysql_fetch_object and mysql_fetch_array?

Mysql_fetch_object() is similar tomysql_fetch_array(), with one difference -an object is returned, instead of an array. Indirectly, that means that you can only access the data by the field names, and not by their offsets (numbers are illegal property names).

  • Question: What are the differences between Get and post methods.

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

  • Question: How can we extract string " " from a string "http:// CLOAKING using regular expression of PHP?

preg_match("/^http:\/\/.+@(.+)$/","http:// CLOAKING ",$matches);echo $matches[1];

  • Question: How can we create a database using PHP and MySQL?

We can create MySQL database with the use of mysql_create_db("Database Name")

  • Question: Can we use include ("xyz.PHP") two times in a PHP page "index.PHP"?

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

  • Question: What are the different tables(Engine) present in MySQL, which one is default?

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

  • Question: What is use of header() function in php ?

The header() function sends a raw HTTP header to a client.We can use herder() function for redirection of pages. It is important to notice that header() must be called before any actual output is seen..

  • Question: How can I execute a PHP script using command line?

Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument.

  • Question: Suppose your Zend engine supports the mode Then how can u configure your PHP Zend engine to support mode ?

In php.ini file:set short_open_tag=on to make PHP support

  • Question: What is htaccess? Why do we use this and Where?

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.

  • Question: How we get IP address of client, previous reference page etc ?


  • Question: What are the reasons for selecting lamp (Linux, apache, MySQL,PHP) instead of combination of other software programs, servers andoperating systems?

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.

  • Question: What is meant by nl2br()?

Inserts HTML line breaks (
) before all newlines in a string.

  • Question:.How can we encrypt and decrypt a data present in a MySQL table using MySQL?


  • Question: How can we encrypt the username and password using PHP?

The functions in this section perform encryption and decryption, and compression and uncompression:
encryption       decryption
ENCRYPT()   Not available
MD5() Not available
OLD_PASSWORD() Not available
PASSWORD()           Not available
SHA() or SHA1()       Not available

  • Question: What are the features and advantages of object-oriented programming?

One of the main advantages of OO programming is its ease of modification; objects can easily be modified and added to a system there by reducing maintenance costs. OO programming is also considered to be better at modeling the real world than is procedural programming. It allows for more complicated and flexible interactions. OO systems are also easier for non-technical personnel to understand and easier for them to participate in the maintenance and enhancement of a system because it appeals to natural human cognition patterns. For some systems, an OO approach can speed development time since manyobjects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easilymodified for a specific system.

  • Question: Shopping cart online validation i.e. how can we configure Paypal,etc.?

Nothing more we have to do only redirect to the payPal url after submit all information needed by paypal like amount,adresss etc.

  • Question: What are the differences between procedure-oriented languages and object-oriented languages?

There are lot of difference between procedure language and object oriented like below
1>Procedure language easy for new developer but complex to understand whole software as compare to object oriented model
2>In Procedure language it is difficult to use design pattern mvc , Singleton pattern etc but in OOP you we able to develop design pattern
3>IN OOP language we able to ree use code like Inheritance ,polymorphism etc but this type of thing not available in procedure language on that our Fonda use COPY and PASTE .

  • Question: What is the use of friend function?

Sometimes a function is best shared among a number of different classes. Such functions can be declared either as member functions of one class or as global functions. In either case they can be set to be friends of other classes, by using a friend specifier in the class that is admitting them. Such functions can use all attributes of the class which names them as a friend, as if they were themselves members of that class. A friend declaration is essentially a prototype for a member function,but instead of requiring an implementation with the name of that class attached by the double colon syntax, a global function or member function of another class provides the match.

  • Question: What are the differences between public, private, protected,static, transient, final and volatile?

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 amethod by prefixing the definition with final. If the class itself is being defined final then it cannot be extended. transient: A transient variable is a variable that may not be serialized.  volatile: a variable that might be concurrently modified by multiple threads should be declared volatile. Variables declared to be volatile will not be optimized by the compiler because their value can change at any time.

  • Question: What are the different types of errors in PHP?

Three are three types of errors:1. Notices: These are trivial,non-critical errors that PHP encounters while executing a script – for example, accessing a variable that has not yet been defined. By default,such errors are not displayed to the user at all – although, as you will see, you can change this default behavior.2. Warnings: These are more serious errors – for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but 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.

  • Question: What is the functionality of the function strstr and stristr?

Strstr Returns part of string from the first occurrence of needle(sub string that we finding out ) to the end of string.
$email= ' CLOAKING ';
$domain = strstr($email, '@');
echo $domain; // prints
here @ is the needle stristr is case-insensitive means able not able to diffrenciate between a and A

  • Question: What are the differences between PHP 3 and PHP 4 and PHP 5?

There are lot of difference among these three version of php
1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come
2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C In PHP5 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

  • Question: How can we convert asp pages to PHP pages?

There are lots of tools available for asp to PHP conversion. you can search Google for that. the best one is available at

  • Question: What is the functionality of the function htmlentities?

Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

  • Question: How can we get second of the current time using date function?

$second = date("s");

  • Question: How can we convert the time zones using PHP?

By using date_default_timezone_get and date_default_timezone_set function on PHP 5.1.0
// Discover what 8am in Tokyo relates to on the East Coast of the US   
// Set the default timezone to Tokyo time: date_default_timezone_set('Asia/Tokyo');   
// Now generate the timestamp for that particular timezone, on Jan 1st, 2000 $stamp = mktime(8, 0, 0, 1, 1, 2000);   
// Now set the timezone back to US/Easternate_default_timezone_set('US/Eastern');   
// Output the date in a standard format (RFC1123), this will print
// Fri, 31 Dec 1999 18:00:00 EST echo '

', date(DATE_RFC1123, $stamp) ,'


  • Question: What is meant by urlencode and urldocode?

URLencode returns a string in which all non-alphanumeric characters except -_. have been replaced with a percent (%) sign followed by two hex digits and spaces encoded as plus (+)
signs. It is encoded the same way that the posted data from a WWW form is encoded, that is the same way as in 
application/x-www-form-urlencoded media type. urldecode decodes any %## encoding in the given string.

  • Question: What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system. unset() makes a variable undefined.

  • Question: How can we get the properties (size, type, width, height) of an image using PHP image functions?

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

  • Question: How can we get the browser properties using PHP?

By using $_SERVER['HTTP_USER_AGENT'] variable.

  • Question: What is the maximum size of a file that can be uploaded using PHP and how can we change this?

By default the maximum size is 2MB. and we can change the following setup at php.iniupload_max_filesize = 2M

  • Question: How can we increase the execution time of a PHP script?

By changing the following setup at php.inimax_execution_time = 30;
Maximum execution time of each script, in seconds

  • 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!

  • Question: 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.

  • Question: How many ways can we get the value of current session id?

id() returns the session id for the current session.

  • Question: 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

  • Question: How can we set and destroy the cookie n php?

By using setcookie(name, value, expire, path, domain); function we can set the cookie in php ; Set the cookies in past for destroy. like setcookie ("user", "sonia", time()+3600); for set the cookie  setcookie("user", "", time()-3600); for destroy or delete the cookies;

  • Question: How many ways we can pass the variable through the navigation between the pages?

GET/QueryString POST

  • Question: What is the difference between ereg_replace() and eregi_replace()?

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 se distinction when matching alphabetic characters.

  • Question: What are the different functions in sorting an array?

Sort(), arsort(),asort(), ksort(),natsort(), natcasesort(),rsort(), usort(),array_multisort(), and uksort().

  • Question: How can we know the count/number of elements of an array?

2 ways
a) sizeof($urarray) This function is an alias of count()
b) count($urarray)

  • Question: what is session_set_save_handler in PHP?

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred. i.e. Storing the session data in a local database.

  • Question: 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.

  • Question: List out some tools through which we can draw E-R diagrams for mysql.

Case Studio,Smart Draw

  • Question: What is Joomla in PHP?

Joomla is an open source content management system. Joomla can be used in PHP as a framework to publish web contents. Joomla allows the user to manage the content of the web pages with ease.