PHP Interview Questions and Answers

PHP Interview Questions and Answers

1.How can we submit from without a submit button?

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form.

2.How many ways we can retrieve the date in result set of mysql Using php?

As individual objects so single record or as a set or arrays.

3.What is the difference between mysql_fetch_object and mysql_fetch_array?

MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array.

4.What is the difference between $message and $$message?

They are both variables. But $message is a variable with a fixed name. $$message is a variable who's name is stored in $message. For example, if $message contains "var", $$message is the same as $var.

5.What are the differences between require and include, include_once?

File will not be included more than once. If we want to include a file once only and further calling of the file will be ignored then we have to use the PHP function include_once().
    This will prevent problems with function redefinitions, variable value reassignments, etc.

6.What are the different tables present in mysql?

Total 5 types of tables we can create

    1. MyISAM

    2. Heap

    3. Merge

    4. InnoDB

    5. ISAM

    6. BDB
MyISAM is the default storage engine as of MySQL 3.23.

7.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. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

8.What is meant by nl2br()?

    Nl2br Inserts HTML line breaks before all newlines in a string string nl2br (string); For example: echo nl2br("god bless
    you") will output "god bless
    you" to your browser.

9.What are the current versions of apache, php, and mysql?

    PHP: php 5.3
    MySQL: MySQL 5.5
    Apache: Apache 2.2

10.What are the reasons for selecting lamp (Linux, apache, mysql, php) instead of combination of other software programs, servers and operating 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.

11.How can we encrypt and decrypt a data present in a mysql table using mysql?

    AES_ENCRYPT () and AES_DECRYPT ()

12.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);

13.What are the different types of errors in php?

 E_ERROR: A fatal error that causes script termination
 E_WARNING: Run-time warning that does not cause script termination
 E_PARSE: Compile time parse error.
 E_NOTICE: Run time notice caused due to error in code
 E_CORE_ERROR: Fatal errors that occur during PHP's initial startup (installation)
 E_CORE_WARNING: Warnings that occur during PHP's initial startup
 E_COMPILE_ERROR: Fatal compile-time errors indication problem with script.
 E_USER_ERROR: User-generated error message.
 E_USER_WARNING: User-generated warning message.
 E_USER_NOTICE: User-generated notice message.
 E_STRICT: Run-time notices.
 E_RECOVERABLE_ERROR: Catchable fatal error indicating a dangerous error
 E_ALL: Catches all errors and warnings

14.What is the functionality of the function htmlentities?

    Answer: 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.

15.What is meant by urlencode and urldocode?

    Urlencode() returns the URL encoded version of the given string. URL coding converts special characters into % signs followed by two hex digits. For example: urlencode("10.00%") will return "10%2E00%25?. URL encoded strings are safe to be used as part of URLs.

16.What is the difference between the functions unlink and unset?

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

17.How can we register the variables into a session?

    We can use the session_register ($ur_session_var) function.

18.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

19.What is the maximum size of a file that can be uploaded using php and how can we change this?

    You can change maximum size of a file set upload_max_filesize variable in php.ini file.

20.How can we increase the execution time of a php script?

    Set max_execution_time variable in php.ini file to your desired time in second.

21.How can we take a backup of a mysql table and how can we restore it.?

Create a full backup of your database: shell> mysqldump tab=/path/to/some/diropt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dir
The full backup file is just a set of SQL statements, so restoring it is very easy:
shell> mysql "."Executed";
mysql_close($link2);

22.How many ways can we get the value of current session id?

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

23.How can we destroy the session, how can we unset the variable of a session?

session_destroy and session_unset

24.How can we destroy the cookie?

Set same the cookie in past

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

26.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)
interestingly if u just pass a simple var instead of a an array it will return 1.

27.What is the maximum length of a table name, database name, and fieldname in mysql?

Database name- 64
Table name -64
Fieldname-64

28.How many values can the SET function of mysql takes?

Mysql set can take zero or more values but at the maximum it can take 64 values

29.What is meant by MIME?

Multipurpose Internet Mail Extensions.WWW ability to recognise 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. This information is incorporated into Web server and browser software, and enables the automatic recognition and display of registered file types.

30.What is meant by PEAR in php?

PEAR is short for "PHP Extension and Application Repository" and is pronounced just like the fruit. The purpose of PEAR is to provide:
A structured library of open-sourced code for PHP users
A system for code distribution and package maintenance
A standard style for code written in PHP
The PHP Foundation Classes (PFC),
The PHP Extension Community Library (PECL),
A web site, mailing lists and download mirrors to support the PHP/PEAR community
PEAR is a community-driven project with the PEAR Group as the governing body.
   
31.What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?

Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_object ( resource result )
Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

32.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?

On the server side, the main difference between GET and POST is where the submitted is stored. The $_GET array stores data submitted by the GET method. The $_POST array stores data submitted by the POST method.On the browser side, the difference is that data submitted by the GET method will be displayed in the browser's address field. Data submitted by the POST method will not be displayed anywhere on the browser.

GET method is mostly used for submitting a small amount and less sensitive data. POST method is mostly used for submitting a large amount or sensitive data.

33.Who is the father of php and explain the changes in php versions?

Rasmus Lerdorf for version changes go to http://php.net/ Marco Tabini is the founder and publisher of php|architect.

34.What is PHP?

PHP Version 3.0 is an HTML-embedded scripting language. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features thrown in. The goal of the language is to allow web developers to write dynamically generated pages quickly.

35.What is the difference between include and require?

If you require a file and it cannot be found, the script will terminate with a fatal error. If you use include then you will get an error but the script will continue to execute. Therefore when the information you wish to reference from another file is essential to the correct running of a page, use require.

36.Is PHP a case sensitive programming language?

PHP is a partially case sensitive programming language. We can use function names, class names in case insensitive manner.

37.What is mean by LAMP?

 LAMP means combination of Linux, Apache, MySQL and PHP.

38.How do you get the user's ip address in PHP?

Using the server variable: $_SERVER['REMOTE_ADDR']

39.How to find the number of elements in an array?

Using count($array) or sizeof($array).

40.How do you make one way encryption for your passwords in PHP?

Using md5 function or sha1 function

41.What is meant by PEAR in php?

PEAR is the next revolution in PHP. This repository is bringing higher level programming to PHP. PEAR is a framework and distribution system for reusable PHP components. It eases installation by bringing an automated wizard, and packing the strength and experience of PHP users into a nicely organised OOP library. PEAR also provides a command-line interface that can be used to automatically install "packages"

42.How can we repair a MySQL table?

The syntex for repairing a mysql table is:

REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED
This command will repair the table specified.
If QUICK is given, MySQL will do a repair of only the index tree.
If EXTENDED is given, it will create index row by row.

43.What is the difference between echo and print statement?

Echo() can take multiple expressions,Print cannot take multiple expressions.Print return true or false based on success or failure whereas echo just does what its told without letting you know whether or not it worked properly.

44.What Is a Session?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.There is only one session object available to your PHP scripts at any time. Data saved to the session by a script can be retrieved by the same script or another script when requested from the same visitor.

   Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.
Session stored in server.

45.Explain about PHP looping?

    Looping statements are used in PHP to execute the code for a developer defined number of times. PHP has these following looping statements they are while, do while, for and for each. Foreach is used to loop a block of code in each element in an array.

46.What is triggers ? Does MySQL supports it ?

    A trigger is a database object which is associated with particular database table. Triggers gets called automatically when particular event(INSERT, UPDATE, DELETE) occurs on table.In MySQL, Triggers gets supported after MySQL 5.0.2

47.What is difference between mysql_connect and mysql_pconnect ?

    Mysql_connect opens up a database connection every time a page is loaded. mysql_pconnect opens up a connection, and keeps it open across multiple requests.Mysql_pconnect uses less resources, because it does not need to establish a database connection every time a page is loaded.

48.What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row() ?

Mysql_fetch_array - Fetch a result row as an associative array and a numeric array.mysql_fetch_object - Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows mysql_fetch_row() - Fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.

49.What are the different types of errors in PHP ?

    Here are three basic types of runtime errors in PHP:

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

    Internally, these variations are represented by twelve different error types

50.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 many objects are standard across systems and can be reused. Components that manage dates, shipping, shopping carts, etc. can be purchased and easily modified for a specific system.

51.what is the use of the function " explode() " in php?

This function is used to split a string by special character or symbol in the string, we must be pass the string and splitting character as parameter into the function.

52.What is use of in_array() function in php ?

in_array used to checks if a value exists in an array

53.How to retrieve the data from MySQL result set ?

using the methods given below 1. mysql_fetch_row. 2. mysql_fetch_array 3. mysql_fetch_object 4. mysql_fetch_assoc

54.differences between GET and POST methods ?

We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .

55.What is SSL ?

SSL stands for Secure Sockets Layer. This is a cryptographic protocols which provide secure communications on the Internet

56.How to calculate the sum of values in an array ?

"array_sum" method used for calculate sum of values in an array

57.What is the use of "ksort" in php?

it is used for sort an array by key in reverse order.

58.What is PHP?

PHP is a server side scripting language commonly used for web applications

59.How to include a file to a php page?

we can include a file using "include() " or "require()" function with as its parameter.

60.What?s the difference between include and require?

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.

61.require_once(), require(), include().What is difference between them?

require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.

62.How do you define a constant?

Using define() directive, like define ("MYCONSTANT",150)

63.What Is a Session?

It can be used to store information on the server for future use

64.How to set cookies in PHP?

Cookies are often used to track user information Syntax: Setcookie(name, value, expire, path, domain); eg:Setcookie(?sample?, ?ram?, time()+3600);

65.Difference between mysql_connect and mysql_pconnect?

There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.

66.How to create a mysql connection?

mysql_connect(servername,username,password);

67.Who is the father of PHP and explain the changes in PHP versions?

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 additionalOOP features
     
68.How can we submit a form without a submit button?

The main idea behind this is to use Java script submit() function in  order 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).
     
69.In how many ways we can retrieve the data in the result set of MySQL using PHP?

You can do it by 4 Ways1. mysql_fetch_row.
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
     
70.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).
     
71.What is the difference between $message and $$message?

It is a classic example of PHP’s variable variables. take the following example.
$message = “Mizan”;$$message = “is a moderator of PHPXperts.”;$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.
     
72.How can we extract string ‘abc.com ‘ from a string ‘http://info@abc.com’ using regular expression of PHP?

preg_match(“/^http:\/\/.+@(.+)$/”,’http://info@abc.com’,$found);
echo $found[1];
     
73.How can we create a database using PHP and MySQL?

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

74.Functions in IMAP, POP3 AND LDAP?

You can find these specific information in PHP Manual.
     
75.How can I execute a PHP script using command line?

As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, “php myScript.php”, assuming “php” is the command to invoke the CLI program.Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.
     
776.Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ?

In php.ini file:
set
short_open_tag=on
to make PHP support
     
77.Shopping cart online validation i.e. how can we configure Paypal,etc.?

We can find the detail documentation about different paypal integration process at the following site
PayPal PHP
SDK : http://www.paypaldev.org
     
78.What is meant by nl2br()?

Inserts HTML line breaks (<BR />) before all newlines in a string string nl2br (string); Returns string with ” inserted before all newlines. For example: echo nl2br(“god bless\n you”) will output “god bless <br /> you” to your browser.
       
79.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.
     
80.How can we get second of the current time using date function?

$second = date(“s”);

81.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.
     
82.What is the difference between the functions unlink and unset?

unlink() deletes the given file from the file system.
unset() makes a variable undefined.
     
83.How can we register the variables into a session?

$_SESSION[’name’] = “Mizan”;
     
84.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 t
     
85.How can we get the browser properties using PHP?

By using
$_SERVER['HTTP_USER_AGENT']
variable.
     
86.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
     
88.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
     
89.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!
     
90.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.

91.How many ways can we get the value of current session id?

session_id() returns the session id for the current session.
     
92.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
     
93.How can we destroy the cookie?

Set the cookie in past.
     
94.How many ways we can pass the variable through the navigation between the pages?

GET/QueryString
POST

95.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 case distinction when matching alphabetic characters.
     
96.What are the different functions in sorting an array?

Sort(), arsort(),
asort(), ksort(),
natsort(), natcasesort(),
rsort(), usort(),
array_multisort(), and
uksort().
     
97.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)
     
98.What is the PHP predefined variable that tells the What types of images that PHP supports?

Though i am not sure if this is wrong or not, With the exif extension you are able to work with image meta data.
     
99.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.
     
100.List out some tools through which we can draw E-R diagrams for mysql?

Case Studio
Smart Draw

101.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.
     
102.What are the difference between abstract class and interface?

Abstract class: abstract classes are the class where one or more methods are abstract but not necessarily all method has to be abstract.
Abstract methods are the methods, which are declare in its class but not define. 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 define by its implemented class.
     
103.How can we send mail using JavaScript?

JavaScript does not have any networking capabilities as it is designed to work on client site. As a result we can not send mails using JavaScript. But we can call the client side mail protocol mailto via JavaScript to prompt for an email to send. this requires the client to approve it.
     
104.How can we repair a MySQL table?

The syntex for repairing a MySQL table is REPAIR TABLENAME, [TABLENAME, ], [Quick],[Extended] This command will repair the table specified if the quick is given the MySQL will do a repair of only the index tree if the extended is given it will create index row by row

105.What are the advantages/disadvantages of MySQL and PHP?

Both of them are open source software (so free of cost), support cross platform. php is faster then ASP and JSP.
     
106.What is the difference between GROUP BY and ORDER BY in Sql?

ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns it should sort the result. If two rows will hawe the same value in col1 it will try to sort them according to col2 and so on.GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same value of column col1. You can use COUNT(col1), SUM(col1), AVG(col1) with it, if you want to count all items in group, sum all values or view average
     
107.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 ‘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.
     
108.What is the functionality of md5 function in PHP?

Calculate the md5 hash of a string. The hash is a 32-character hexadecimal number. I use it to generate keys which I use to identify
users etc. If I add random no techniques to it the md5 generated now will be totally different for the same string I am using.
     
109.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 thata) data is delimited
b) columns and data matched correctly

0 comments:

Post a Comment