#php# interview questions

68
PHP interview questions, Part 1 Web dev interview questions Feel free to post the answers and discuss the questions in the comments. Mizanur Rahman also posted some detailed answers on his blog. 1. 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? 2. Who is the father of PHP and explain the changes in PHP versions? 3. How can we submit a form without a submit button? 4. In how many ways we can retrieve the date in the result set of mysql using PHP? 5. What is the difference between mysql_fetch_object and mysql_fetch_array? 6. What is the difference between $message and $$message? 7. How can we extract string ‘techinterviews.com ‘ from a string ‘http://www.techinterviews.com’ using regular expression of PHP? 8. How can we create a database using PHP and mysql? 9. What are the differences between require and include, include_once? 10. Can we use include (”techinterviews.php”) two times in a PHP page “makeit.PHP”? 11. 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)) ? 12. Functions in IMAP, POP3 AND LDAP? 13. How can I execute a PHP script using command line? 14. Suppose your Zend engine supports the mode <? ?> Then how can u configure your PHP Zend engine to support <?PHP ?> mode ? 15. Shopping cart online validation i.e. how can we configure Paypal, etc.? 16. What is meant by nl2br()? 17. Draw the architecture of Zend engine? 18. What are the current versions of apache, PHP, and mysql? 19. What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of combination of other software programmes, servers and operating systems? 20. How can we encrypt and decrypt a data present in a mysql table using mysql? 21. How can we encrypt the username and password using PHP? 22. What are the features and advantages of object-oriented programming? 23. What are the differences between procedure-oriented languages and object-oriented languages? 1

Upload: ynpatil

Post on 15-Jun-2015

1.009 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: #PHP# Interview Questions

PHP interview questions, Part 1

Web dev interview questions

Feel free to post the answers and discuss the questions in the comments. Mizanur Rahman also posted some detailed answers on his blog.

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

2. Who is the father of PHP and explain the changes in PHP versions? 3. How can we submit a form without a submit button? 4. In how many ways we can retrieve the date in the result set of mysql using

PHP? 5. What is the difference between mysql_fetch_object and mysql_fetch_array? 6. What is the difference between $message and $$message? 7. How can we extract string ‘techinterviews.com ‘ from a string

‘http://www.techinterviews.com’ using regular expression of PHP? 8. How can we create a database using PHP and mysql? 9. What are the differences between require and include, include_once? 10. Can we use include (”techinterviews.php”) two times in a PHP page

“makeit.PHP”? 11. 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)) ?

12. Functions in IMAP, POP3 AND LDAP? 13. How can I execute a PHP script using command line? 14. Suppose your Zend engine supports the mode <? ?> Then how can u

configure your PHP Zend engine to support <?PHP ?> mode ? 15. Shopping cart online validation i.e. how can we configure Paypal, etc.? 16. What is meant by nl2br()? 17. Draw the architecture of Zend engine? 18. What are the current versions of apache, PHP, and mysql? 19. What are the reasons for selecting lamp (linux, apache, mysql, PHP) instead of

combination of other software programmes, servers and operating systems? 20. How can we encrypt and decrypt a data present in a mysql table using mysql? 21. How can we encrypt the username and password using PHP? 22. What are the features and advantages of object-oriented programming? 23. What are the differences between procedure-oriented languages and object-

oriented languages? 24. What is the use of friend function? 25. What are the differences between public, private, protected, static, transient,

final and volatile? 26. What are the different types of errors in PHP? 27. What is the functionality of the function strstr and stristr? 28. What are the differences between PHP 3 and PHP 4 and PHP 5? 29. How can we convert asp pages to PHP pages? 30. What is the functionality of the function htmlentities? 31. How can we get second of the current time using date function? 32. How can we convert the time zones using PHP? 33. What is meant by urlencode and urldocode? 34. What is the difference between the functions unlink and unset? 35. How can we register the variables into a session? 36. How can we get the properties (size, type, width, height) of an image using

PHP image functions? 37. How can we get the browser properties using PHP?

1

Page 2: #PHP# Interview Questions

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

39. How can we increase the execution time of a PHP script? 40. How can we take a backup of a mysql table and how can we restore it. ? 41. How can we optimize or increase the speed of a mysql select query? 42. How many ways can we get the value of current session id? 43. How can we destroy the session, how can we unset the variable of a session? 44. How can we destroy the cookie? 45. How many ways we can pass the variable through the navigation between the

pages? 46. What is the difference between ereg_replace() and eregi_replace()? 47. What are the different functions in sorting an array? 48. How can we know the count/number of elements of an array? 49. What is the PHP predefined variable that tells the What types of images that

PHP supports? 50. How can I know that a variable is a number or not using a JavaScript? 51. List out some tools through which we can draw E-R diagrams for mysql. 52. How can I retrieve values from one database server and store them in other

database server using PHP? 53. List out the predefined classes in PHP? 54. How can I make a script that can be bilanguage (supports English, German)? 55. What are the difference between abstract class and interface? 56. How can we send mail using JavaScript?

1. chandu said,

mysql_fetch_object() is similar to mysql_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).

visit http://in2.php.net/mysql_fetch_objectandhttp://in2.php.net/mysql_fetch_arrayfor more info

2. chandu said,

Answer for Q6) can be found athttp://www.phpbuilder.com/columns/robert20000928.php3

3. chandu said,

Answer to Q7)

$exploded[1] should have abc.com

4. chandu said,

answer to Q8)mysql_create_db() should work

2

Page 3: #PHP# Interview Questions

5. chandu said,

Answer to Q9)require_once(),include_once() both the functions include and evalute the specified file only onceand if the specified file is opened previous to the present call occurrance, it will not be done again.But require() and include() will do it as many times they are asked to do.

6. chandu said,

answer to q10) Yes we can include that many times we want, but here are some things to make sure of:(including abc.PHP, the file names are case-sensitive)there shouldnt be any duplicate function names, means there should not be functions or classes or variables with the same name in abc.PHP and makeit.php

7. chandu said,

correction to my previous comment:I’v specified functions,classes and variables, exactly what I meant with variables is…u’v tomake sure that the variables wont over write each other.

8. chandu said,

Answer to Q)11Refer the Pagehttp://dev.mysql.com/doc/mysql/en/storage-engines.html

9. meenakshi said,

get is like query string all the variables will be displayed in he urlwhere as post is the standard way of sending th evariables

10.meenakshi said,

Ques 2Father of php is Rasmus Lerdorf and for version info and changes see this linkhttp://www.php.net/ChangeLog-4.php#4.1.0

11.meenakshi said,

q5mysql_fetch_object is like fetching value from a recordsetand mysql_fetch_array is gettin array’s value

12.sukhbir said,

ans_16

3

Page 4: #PHP# Interview Questions

nl2br() inserts html in string

echo nl2br(”god bless \n you”);

outputgod blessyou

13.D R Jadav said,

Answer for Q.1

When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.

14.D R Jadav said,

Answer of Question 1:When we submit a form, which has the GET method it displays pair of name/value used in the form at the address bar of the browser preceded by url. Post method doesn’t display these values.

15.D R Jadav said,

Answer of Question no 5 :

mysql_fetch_object() is similar to mysql_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). Note: Field names returned by this function are case-sensitive.field;/* this is invalid */echo $row->0;?>

16.D R Jadav said,

Answer of question no 6:$message is variable whereas $$message is Dynamic variable.eg.$user=”bob”

is equivalent to

$holder=”user”;$$holder=”bob”;

17.D R Jadav said,

Answer of Question 7 :

4

Page 5: #PHP# Interview Questions

Use the function split split(“@”,”http://[email protected]”) which returns an array any second element of the returned array will hold the value as abc.com.

18.D R Jadav said,

Answer of Question no 8 :

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

19.D R Jadav said,

Answer of Question no 9 :

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.

20.D R Jadav said,

Answer of Question no 10 :

Yes we can use include() more than once in same page.

21.D R Jadav said,

Answer of Question no 11 :

Table Types are· ISAM(Index Sequential Access Method)· MyISAMo Statico Dynamico Compress· Merge· Heap (Fastest tables because it stores in to the RAM)· BDB· InnoDB (Transaction safe table)

When you fire the above create query MySQL will create the Dynamic table.

22.D R Jadav said,

Answer of Question no 13 :

13. How can I execute a PHP script using command line?Through php parse you can execute PHP script using command line. By default location of php parser is /var/www/html so set the path of this directory and just use as following#php sample.php

5

Page 6: #PHP# Interview Questions

23.D R Jadav said,

Answer of Question no 16 :

Returns string with ” inserted before all newlines

24.D R Jadav said,

Answer of Question no 18 :

For information about latest version of Apache, Php and Mysql please visits the following sites respectively.

www.apache.orgwww.php.netwww.mysql.com

25.D R Jadav said,

Answer of Question no 21 :

You can encrypt a password with the followingMysql>SET PASSWORD=PASSWORD(“Password”);

26.D R Jadav said,

Answer of Question no 26 :

Three are three types of errors 1) Fatal errors 2) Parser errors 3) Startup errors.

27.D R Jadav said,

Answer of Question no 27 :

string strstr ( string str1, string str2) this function search the string str1 for the first occurrence of the string str2 and returns the part of the string str1 from the first occurrence of the string str2. This function is case-sensitive and for case-insensitive search use stristr() function.

28.D R Jadav said,

Answer of Question no 29 :

You can download asp2php front end application from the site http://asp2php.naken.cc.

29.Praveen said,

nl2br(PHP 3, PHP 4 )

6

Page 7: #PHP# Interview Questions

nl2br — Inserts HTML line breaks before all newlines in a stringQUES TION 16string nl2br ( string string)

Returns string with ” inserted before all newlines.

this will output :foo isn’tbar

30.Grant Harding said,

Is it really in the best interest of both employers and job-seekers to have the answers for this available? If you can’t answer many of these basic questions, I hope you aren’t aiming for a job in the field. These simple answers come with experience and practice.

31.Shatabdi said,

56. How can we send mail using JavaScript?The answer for this question

function myfunction(form){tdata=document.myform.tbox1.value;location=”mailto:[email protected]?subject=”+tdata+”/MYFORM”;return true;}

32.Shatabdi said,

53.List out the predefined classes in PHP?Predefined Classes1. Standard Defined ClassesThese classes are defined in the standard set of functions included in the PHP build.

a. DirectoryThe class from which dir() is instantiated.

b.stdClass

2.Ming Defined ClassesThese classes are defined in the Ming extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

a.swfshape

b. swffill

c. swfgradient

7

Page 8: #PHP# Interview Questions

d. swfbitmap

e. swftext

f. swftextfield

g. swffont

h. swfdisplayitem

i. swfmovie

j. swfbutton

k. swfaction

l. swfmorph

m. swfsprite

3. Oracle 8 Defined ClassesThese classes are defined in the Oracle 8 extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

a. OCI-Lobb. OCI-Collection

4. qtdom Defined ClassesThese classes are defined in the qtdom extension, and will only be available when that extension has either been compiled into PHP or dynamically loaded at runtime.

a. QDomDocument

b. QDomNode

33.Bharati Raul said,

1) What are the differences between Get and postmethods in form submitting, give the case where we canuse get and we can use post methods?

Ans : When you want to send short or small data,not containing ASCII characters, then you can use “GET”Method. But for long data sending say more then 100character you can use “POST” method.

Once most imp diff is when you are sending the form with“Get” method. You can see the output which you are sendingin the addressbar. Whereas if you send the form with “POST”

8

Page 9: #PHP# Interview Questions

method then user can not see that information.————————————————–

2) Who is the father of PHP and explain the changes inPHP versions?

Ans : Rasmus Lerdorf is the father of PHP————————————————–

3) How can we submit a form without a submit button?

Ans : I can submit a form in many ways, for e.g.1. When user click on checkbox, or drop down2. When user click on radio button3. At the end of the form I will type “Click hereto submit” & link text to the processing file————————————————–

4) In how many ways we can retrieve the date inthe result set of mysql using PHP?

————————————————–5) What is the difference between mysql_fetch_objectand mysql_fetch_array?

Ans :Speed-wise, the function is identical to mysql_fetch_array(),and almost as quick as mysql_fetch_row() (the difference isinsignificant).

mysql_fetch_object() is similar to mysql_fetch_array(),with one difference - an object is returned,instead of an array. Indirectly, that means that you can onlyaccess the data by the field names, and not by their offsets(numbers are illegal property names).————————————————–

6) What is the difference between $message and$$message?Ans : $message is variable whereas $$message is dynamic varibale————————————————–

34.Bharati Raul said,

7) How can we extract string ‘abc.com ‘ from a string‘http://[email protected]’ using regular expression of PHP?Ans : echo substr(”http://[email protected]”,12,19);————————————————–

8) How can we create a database using PHP and mysql?ANS : mysql_create_db(”Database_Name”);————————————————–

9

Page 10: #PHP# Interview Questions

9) What are the differences between require and include, include_once?ANS :include() & require() - includes the file during the execution of the script.but is there is any problem include() generate a warning message where asrequire() generates the fatal error.include_once() & require_once() - same as include() and require() butif file is already included then does not produce any error or notinclude that file again————————————————–

10) Can we use include (”abc.PHP”) two times in a PHPpage “makeit.PHP”?

Ans : Yes we can include two times and more then two times also————————————————–

11) What are the different tables present in mysql,which type of table is generated when we are creatinga table in the following syntax: create tableemployee(eno int(2),ename varchar(10)) ?

Ans :Total 5 types of tables we can create1. MyISAM2. Heap3. Merge4. INNO DB5. ISAMMyISAM is the default storage engine as of MySQL 3.23.————————————————–

35.Kumar said,

What is meant by urlencode and urldocode?string urlencode(str)where str contains a string like this “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 someurl.com?var=hello%worldstring urldocode(str)this will simple decode the GET variable’s valueLike it echo (urldecode($_GET_VARS[var])) will o/p “Hello world”

36.Kumar said,

How can we destroy the cookie?Set the cookie in past

37.Kumar said,

What is the difference between the functions unlink and unset?unlink is a function for file system handling. It will simply delete the file in contextunset will set UNSET the variable. e.g

10

Page 11: #PHP# Interview Questions

38.Kumar said,

How can we register the variables into a session?session_register($ur_session_var);

39.Kumar said,

How can we know the count/number of elements of an array?2 waysa) 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.

40.ramesh said,

Q 20;

AES_ENCRYPT() and AES_DECRYPT()

41.Mikhail Esteves said,

Question 56: This question is wrong. You aren’t really ’sending mail’ when doing a ‘mailto’ and so it’s a misleading question… A smart candidate would just say “It’s not possible” and you may write him off.

42.Pujitha Sendanayake said,

some information about zend engine.

http://www.mlinux.org/projects/present/zend/http://www.zend.com/zend/zend-engine-summary.phphttp://www.zend.com/store/products/zend-engine.php

43.Pujitha Sendanayake said,

Q46-

eregi_replace() function is identical to ereg_replace() except that this ignores case distinction when matching alphabetic characters.

44.Pujitha Sendanayake said,

q47.Sorting functions in PHP,asort-http://www.php.net/manual/en/function.asort.phparsort-http://www.php.net/manual/en/function.arsort.phpksort-http://www.php.net/manual/en/function.ksort.phpkrsort-http://www.php.net/manual/en/function.krsort.phpuksort-http://www.php.net/manual/en/function.uksort.phpsort-http://www.php.net/manual/en/function.sort.phpnatsort-http://www.php.net/manual/en/function.natsort.phprsort-http://www.php.net/manual/en/function.rsort.php

11

Page 12: #PHP# Interview Questions

45.Rahul Amrutkar said,

Ans Q. 52 for this purpose we have first read the data from one server into session varaibles. and then connect to other server and simply insert the data into the database

46.Rahul Amrutkar said,

Q. 6$message is simple variable.$$message is reference variable.

47.Mallu Indian said,

Some answers may be wrong.I got the job anyway, so shouldnt be completly crap. ;-)

puremango.co.uk

1. WHAT IS THE DIFFERENCE BETWEEN GET & POST?

Get is an Idompotent method. (Idompotent: The side-effects of N > 0 identical requests is the same as for a single request. The methods GET, HEAD, PUT and DELETE share this property.)”GET” is basically for just getting (retrieving: quering db for data & retriving) data whereas “POST” may involve anything, like storing or updating data, or ordering a product, or sending E-mail. In GET form data is to be encoded (by a browser) into a URL while the latter means that the form data is to appear within a message body. For GET in IE, Maximum URL Length Is 2,083 Characters in Internet Explorer (Q208427) or approximatly 1k.

2. WHO IS THE FATHER OF PHP AND WHAT IS THE CURRENT IN PHP & MYSQLVERSION?

Rasmus Lerdorf.PHP 5.1. BetaMySQL 5.0

3. HOW CAN WE SUBMIT A FORM WITHOUT A SUBMIT BUTTON?

form.submit();

4. IN HOW MANY WAYS WE CAN RETRIEVE THE DATE IN THE RESULT SET OF MYSQL USING PHP?

mysql_fetch_array — Fetch a result row as an associative array, a numeric array, or bothmysql_fetch_assoc — Fetch a result row as an associative arraymysql_fetch_object — Fetch a result row as an objectmysql_fetch_row — Get a result row as an enumerated array

12

Page 13: #PHP# Interview Questions

5.WHAT IS THE DIFFERENCE BETWEEN MYSQL_FETCH_OBJECT AND MYSQL_FETCH_ARRAY?

mysql_fetch_array — Fetch a result row as an associative ARRAY, a numeric array, or bothmysql_fetch_object — Fetch a result row as an OBJECT

6. WHAT IS THE DIFFERENCE BETWEEN $MESSAGE AND $$MESSAGE?

$message is a variable$$message is a variable variable.A variable variable allows us to change the name of a variable dynamically.

7. HOW CAN WE EXTRACT STRING ‘ABC.COM’ FROM A STRING ‘HTTP://[email protected]’ USING REGULAR EXPRESSION OF PHP?

8. HOW CAN WE CREATE A DATABASE USING PHP AND MYSQL?

$sql = ‘CREATE DATABASE my_db’;if (mysql_query($sql, $link)){echo “Database my_db created successfully\n”;}else{echo ‘Error creating database: ‘ . mysql_error() . “\n”;}

9. WHAT ARE THE DIFFERENCES BETWEEN REQUIRE AND INCLUDE, INCLUDE_ONCE?

All three are used to an include file into the current page. It is faster than include().If the file is not present, require(), calls a fatal error, while in include() does not.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. It des not call a fatal error if file not exists. require_once() does the same as include_once(), but it calls a fatal error if file not exists.

10. CAN WE USE INCLUDE (”ABC.PHP”) TWO TIMES IN A PHP PAGE “MAKEIT.PHP”?

YES

11. 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)) ?

MyISAM: This is default. Based on Indexed Sequntial Access Method. The above SQL will create a MyISA table.

13

Page 14: #PHP# Interview Questions

ISAM : sameHEAP : Fast data access, but will loose data if there is a crash. Cannot have BLOB, TEXT & AUTO INCRIMENT fieldsBDB : Supports Transactions using COMMIT & ROLLBACK. Slower that others.InoDB : same as BDB

12. FUNCTIONS IN IMAP, POP3 AND LDAP?

imap_body — Read the message bodyimap_check — Check current mailboximap_delete — Mark a message for deletion from current mailboximap_mail — Send an email message

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

14. SUPPOSE YOUR ZEND ENGINE SUPPORTS THE MODE THEN HOW CAN U CONFIGURE YOUR PHP ZEND ENGINE TO SUPPORT MODE ?

Its already supported.

15. WHAT IS MEANT BY NL2BR()?

Returns string with after inserting HTML line breaks before all newlines in a string

16. HOW CAN WE ENCRYPT AND DECRYPT A DATA PRESENT IN A MYSQL TABLE USING MYSQL?

AES_ENCRYPT(str,key_str) , AES_DECRYPT(crypt_str,key_str)

17. ENCRYPTION FUNCTIONS IS PHP

CRYPT()MD5()

18. WHAT ARE THE DIFFERENCES BETWEEN PUBLIC, PRIVATE, PROTECTED, STATIC, TRANSIENT, FINAL AND VOLATILE?

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

14

Page 15: #PHP# Interview Questions

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 behaviour is to display them to the user when they take place.

Internally, these variations are represented by twelve different error types

20. WHAT IS THE FUNCTIONALITY OF THE FUNCTIONS STRSTR() AND STRISTR()?

string strstr ( string haystack, string needle )Returns part of haystack string from the first occurrence of needle to the end of haystack.

$email = ‘[email protected]’;$domain = strstr($email, ‘@’);echo $domain; // prints @example.com

stristr() is the case insensitive version of strstr()

21. DIFFERENCE BETWEEN HTMLENTITIES() AND HTMLSPECIALCHARS()]

htmlspecialchars : Convert some special characters to HTML entities (Only the most widley used)htmlentities : Convert ALL special characters to HTML entities

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

urldocode : Decodes URL-encoded string

23. WHAT IS THE DIFFERENCE BETWEEN THE FUNCTIONS UNLINK AND UNSET?

unlink: is used to delete a fileunset is used to destroy an eralier declared variable

24. HOW CAN WE REGISTER THE VARIABLES INTO A SESSION?

$_SESSION[’name’] = “Chinmay”;

To destroy a session: unset($_SESSION[’name’]);

25. HOW CAN WE GET THE PROPERTIES (SIZE, TYPE, WIDTH, HEIGHT) OF AN IMAGE USING PHP IMAGE FUNCTIONS?

15

Page 16: #PHP# Interview Questions

getimagesize — Get the size of an imageimage_type_to_extension — Get file extension for image typeimagesx — Get image widthimagesy — Get image height

26. UPLOAD FILE SIZE

In Php.ini file: upload_max_filesize integer

The maximum size of an uploaded file.When an integer is used, the value is measured in bytes.

27. HOW CAN WE INCREASE THE EXECUTION TIME OF A PHP SCRIPT?

Use set_time_limit(int) where int is the number of seconds forexecution of the script. If it’s set to 0 it’s unlimited. Default valueis 30.

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

Utility 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-infoDon’t write table creation information (the CREATE TABLE statement).-d, –no-dataDon’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!

29. OPTIMISING QUERIES

First, one thing that affects all queries: The more complex permission system setup you have, the more overhead you get.If you do not have any GRANT statements done, MySQL will optimise the permission checking somewhat. So if you have a very high volume it may be worth the time to avoid grants. Otherwise, more permission check results in a larger overhead.

30. COOKIES

setcookie(”variable”,”value”,”time”);

variable - name of the cookie variablevariable - value of the cookie variable

16

Page 17: #PHP# Interview Questions

time - expiry timeExample: setcookie(”test”,$i,time()+3600);

Test - cookie variable name$i - value of the variable ‘Test’time()+3600 - denotes that the cookie will expire after an one hour

31. HOW TO RESET/DESTROY A COOKIE

Reset a cookie by specifying expiry timeExample: setcookie(”test”,$i,time()-3600); // already expired time

Reset a cookie by specifying its name onlysetcookie(”test”);

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

33. WHAT TYPES OF IMAGES THAT PHP SUPPORTS?

imagetypes — Return the image types supported by this PHP buildThis function returns a bit-field corresponding to the image formats supported by the version of GD linked into PHP. The following bits are returned, IMG_GIF | IMG_JPG | IMG_PNG | IMG_WBMP | IMG_XPM. To check for PNG support, for example, do this: Example 1. imagetypes() example

34. CHECK IF A VARIABLE IS INTEGER IN JAVASCRIPT

var myValue =9.8;if(parseInt(myValue)== myValue)alert(’Integer’);elsealert(’Not’);

35. TOOLS USED FOR DRAWING ER DIAGRAMS.

Case StudioSmart Draw

48.matts said,

None of you got the Q7 right… you need to pay attentionthe question clearly satates that a _regex_ has to be used….

49.mahesh said,

I got most of these questions when i attended a interview at brainay consulting, hyd. too many on regex. what is it?

17

Page 18: #PHP# Interview Questions

50.u24 said,

eek.. my php was removed.. ah well.

51.Richa said,

Q. How can we increase the execution time of a PHP script?ans. By the use of void set_time_limit ( int seconds)Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.

When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

Q. How can I know that a variable is a number or not using a JavaScript?ans. bool is_numeric ( mixed var)Returns TRUE if var is a number or a numeric string, FALSE otherwise.

Q.How can I execute a PHP script using command line?ans . Check the following url: http://www.sitepoint.com/article/php-command-line-1

Q.What is meant by nl2br()?ans. nl2br — Inserts HTML line breaks before all newlines in a stringDescriptionstring nl2br ( string string)

Returns string with ” inserted before all newlines.

Note: Starting with PHP 4.0.5, nl2br() is now XHTML compliant. All versions before 4.0.5 will return string with ” inserted before newlines instead of ”.

Example 1. using nl2br()

this will output :

foo isn’tbar

52.Subir said,

Ans (14)

In php.ini file:

set

short_open_tag=on

18

Page 19: #PHP# Interview Questions

to make PHP support

53.parmanand said,

any on can tell me how can we recieve textfield valu on next page in php when set global off for security purpuse, without usin GET POST REQUEST HTTP_VARS global arrays

54.Viral Hirpara said,

Question No. 7

Answer,

preg_match(”|[^@]*@(.*)|im”, $text, $output);

$output will give result in second index of array, means $output[1] is answer.

55.Arvind said,

For Q#1

What are "Get" and "Post"? Get and Post are methods used to send data to the server: With the Get method, the browser appends the data onto the URL. With the Post method, the data is sent as "standard input."Major DifferenceIn simple words, in POST method data is sent by standered input (nothingshown in url when posting while in GET method data is sent through query string.ex:Assume we are logging in with username and password.GET: we are submitting a form to login.php, when we do ’submit’ or similaraction to post the form values are sent through ‘visible’ query string (notice‘../login.php?username&password’ as url when executing the script login.php)andis retrieved by login.php by $_GET[’username’] and $_GET[’password’].POST :we are submitting a form to login.php, when we do ’submit’ orsimilar action to post the form, values are sent through ‘invisible’ standeredinput (notice ‘../login.php’) and is retrieved by login.php by $_POST[’username’]and $_POST[’password’].POST is assumed more secure and we can send lot more data than that of GETmethod is limited(they say Internet Explorer can take care of maximum 2083 characteras a query string).

56.Satnam said,

Wow, wonderful answers on php questions. This is really helpful for the php candidates willing to appear for an interview

19

Page 20: #PHP# Interview Questions

57.PHP interview questions < TechInterviews.com said,

[…] 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 Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems. […]

58.ShailC said,

HI I am working on a website and am trying to make an online surveyusing PHP and MySQL.I have a few problems:1. A requirement for the survey is that it asks questions in several pages (first a set of 5 Qs and then click Continue and then again next 5 and again Continue and so on)I know how to send data to database and the values to different colomns but I dont know how to send data to same row for one person….once it goes to next page (on clicking continue) the data is sent into a new row and rest of the fields that were filled on previous page are left blank.Please let me know how to send the data to same row till one whole cycle is completed and start sending data to new row when a new user starts the survey.2. I need PHP script for reading the top ten values and minimum ten values of a colomn and take their average.3. I also want script for rating on scale of 1-7 and yes no percentage.

I would be very thankful if some1 can provide me technical help regarding this.

Thanks a lot

59.Ashik Rahman said,

preg_match(”/^(http:\/\/)?([^\/]+)/i”,“[email protected]”, $matches);$host = $matches[2];preg_match(”/[^\@.\/]+\.[^\.\/]+$/”, $host, $matches);echo “domain name is: {$matches[0]}\n”;

60.shyambabu said,

6th question answer is $message and $$messageboth are variable declarations.$message=”ValueA”$$message is equal to $($message)=$ValueA

61.tarangini said,

Many of these questions i faced in interview when i attend an interview in technofy .These questions r very usefull to us.

62.Vikas Bhambi said,

20

Page 21: #PHP# Interview Questions

These are really “Short BUT Sufficient” answers on php questions. It is really helpful for the Freshers willing to appear for an interview for PHP.

63.Slava said,

How can we extract string ‘abc.com ‘ from a string ‘http://[email protected]’ using regular expression of PHP?

preg_match(’/^http:\/\/.+@(.+)$/’,'http://[email protected]’,$found);echo $found[1];

64.Slava said,

How can we register the variables into a session?

$_SESSION[’var’] = ‘value’;

Old way (deprecated):$var = ‘value’;session_register(’var’);

65.PHP Docs said,

How can I execute a PHP script using command line?

#php -F

66.Carrie Underwood said,

56. How can we send mail using JavaScript?

document.sendeamil.submit();

67.Carrie Underwood said,

56. How can we send mail using JavaScript?

document.sendeamil.submit();

68.Carrie Underwood said,

50. How can I know that a variable is a number or not using a JavaScript?

Definition and UsageThe isNaN() function is used to check if a value is not a number.

SyntaxisNaN(number)

Parameter Descriptionnumber Required. The value to be tested

21

Page 22: #PHP# Interview Questions

69.Jesse said,

Q7)

preg_match(”/^(http:\/\/info@)?([^\/]+)/i”,”http://[email protected]”, $data);echo $data[2];

70.Mohammed Ismail said,

Question :

Difference between mysql_connect and mysql_pconnnect

71.skonealone said,

Hi all..here are the answer for most of the questions post..

1. 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?Ans :-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.

2. Who is the father of php and explain the changes in php versions?Ans :-Rasmus Lerdorf for version changes goto http://php.net/

3. How can we submit from without a submit button?Ans:-Trigger the JavaScript code on any event ( like onselect of drop down list box, onfocus, etc ) document.myform.submit();This will submit the form.

4. How many ways we can retrieve the date in result set of mysql using php?Ans:-As individual objects so single record or as a set or arrays.

5. What is the difference between mysql_fetch_object and mysql_fetch_array?Ans:-MySQL fetch object will collect first single matching record where mysql_fetch_array will collect all matching records from the table in an array

6. What is the difference between $message and $$message?Ans:-Both are variables only$message is a variable and if used with print statement, the content of the $message variable will be displayed. Where as with $$message variable, the content of the $message will also be treated as variable and the content of that variable will be displayed. For ex: If $message contains “var”, then it displays the content of $var on the screen.

22

Page 23: #PHP# Interview Questions

7. How can we extract string ‘abc.com ‘ from a string ‘http://[email protected]’ using regular _expression of php?Ans:-preg_match(”/^(http:\/\/info@)?([^\/]+)/i”,”http://[email protected]”, $data);echo $data[2];

Use the function split split(“@”,”http://[email protected]”) which returns an array any second element of the returned array will hold the value as abc.com.

8. How can we create a database using php and mysql?Ans:-mysql_create_db()

9. What are the differences between require and include, include_once?Ans:-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.

10. Can we use include (”abc.php”) two times in a php page “makeit.php”?Ans:-Yes we can include..

11. 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)) ?Ans:-Total 5 types of tables we can create1. MyISAM2. Heap3. Merge4. INNO DB5. ISAMMyISAM is the default storage engine as of MySQL 3.23.

Table Types are· ISAM(Index Sequential Access Method)· MyISAMo Statico Dynamico Compress· Merge· Heap (Fastest tables because it stores in to the RAM)· BDB· InnoDB (Transaction safe table)

When you fire the above create query MySQL will create the Dynamic table.http://dev.mysql.com/doc/mysql/en/storage-engines.htmlMyISAM Table Type is created, if u not specified any table type then default will be applied and MyISAM is default

13. How can I execute a PHP script using command line?Ans:-

23

Page 24: #PHP# Interview Questions

Through php parse you can execute PHP script using command line. By default location of php parser is /var/www/html so set the path of this directory and just use as following#php sample.php

16. What is meant by nl2br()?Ans:-nl2br() inserts html in stringecho nl2br(”god bless \n you”);

output–god blessyou

Returns string with ‘’ inserted before all newlines

20. How can we encrypt and decrypt a data present in a mysql table using mysql?Ans:-AES_ENCRYPT() and AES_DECRYPT()

21. How can we encrypt the username and password using PHP?Ans:-You can encrypt a password with the followingMysql>SET PASSWORD=PASSWORD(”Password”);

26. What are the different types of errors in PHP?Ans:-Three are three types of errors 1) Fatal errors 2) Parser errors 3) Startup errors.

27. What is the functionality of the function strstr and stristr?Ans:-string strstr ( string str1, string str2) this function search the string str1 for the first occurrence of the string str2 and returns the part of the string str1 from the first occurrence of the string str2. This function is case-sensitive and for case-insensitive search use stristr() function.

28. What are the differences between PHP 3 and PHP 4 and PHP 5?Ans:-for this ans goto http://php.net and check the version changes

29. How can we convert asp pages to PHP pages?Ans:-You can download asp2php front end application from the site http://asp2php.naken.cc.

33. What is meant by urlencode and urldocode?Ans:-string urlencode(str)where str contains a string like this “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 someurl.com?var=hello%world

24

Page 25: #PHP# Interview Questions

string urldocode(str)this will simple decode the GET variable’s valueLike it echo (urldecode($_GET_VARS[var])) will output “Hello world”

34. What is the difference between the functions unlink and unset?Ans:-unlink is a function for file system handling. It will simply delete the file in contextunset will set UNSET the variable. e.g

35. How can we register the variables into a session?Ans:-Yes we cansession_register($ur_session_var);

42. How many ways can we get the value of current session id?ans:-session_id() returns the session id for the current session.

43. How can we destroy the session, how can we unset the variable of a session?Ans:-session_unregister — Unregister a global variable from the current sessionsession_unset — Free all session variables

44. How can we destroy the cookie?Ans:-Set the cookie in past

45. How many ways we can pass the variable through the navigation between the pages?Ans:-GET or QueryString and POST

46. What is the difference between ereg_replace() and eregi_replace()?Ans:-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.

47. What are the different functions in sorting an array?Ans:-Sorting functions in PHP,asort-http://www.php.net/manual/en/function.asort.phparsort-http://www.php.net/manual/en/function.arsort.phpksort-http://www.php.net/manual/en/function.ksort.phpkrsort-http://www.php.net/manual/en/function.krsort.phpuksort-http://www.php.net/manual/en/function.uksort.phpsort-http://www.php.net/manual/en/function.sort.phpnatsort-http://www.php.net/manual/en/function.natsort.phprsort-http://www.php.net/manual/en/function.rsort.php

25

Page 26: #PHP# Interview Questions

48. How can we know the count/number of elements of an array?Ans:-2 waysa) 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.

53. List out the predefined classes in PHP?Ans:-1. Standard Defined ClassesThese classes are defined in the standard set of functions included in the PHP build.

a. DirectoryThe class from which dir() is instantiated.

b.stdClass

2.Ming Defined ClassesThese classes are defined in the Ming extension, and will only be available when thatextension has either been compiled into PHP or dynamically loaded at runtime.

a.swfshape

b. swffill

c. swfgradient

d. swfbitmap

e. swftext

f. swftextfield

g. swffont

h. swfdisplayitem

i. swfmovie

j. swfbutton

k. swfaction

l. swfmorph

m. swfsprite

26

Page 27: #PHP# Interview Questions

3. Oracle 8 Defined ClassesThese classes are defined in the Oracle 8 extension, and will only be available whenthat extension has either been compiled into PHP or dynamically loaded at runtime.

a. OCI-Lobb. OCI-Collection

4. qtdom Defined ClassesThese classes are defined in the qtdom extension, and will only be available when thatextension has either been compiled into PHP or dynamically loaded at runtime.

a. QDomDocument

b. QDomNode

56. How can we send mail using JavaScript?Ans:-No You can’t send mail using Javascript but u can execute a client side email client to send the email using mailto: code.

Using clientside email clientfunction myfunction(form){tdata=document.myform.tbox1.value;location=”mailto:[email protected]?subject=”+tdata+”/MYFORM”;return true;}

This question is wrong. You aren’t really ’sending mail’ when doing a ‘mailto’ and so it’s a misleading question… A smart candidate would just say “It’s not possible” and you may write him off.

57. What is meant by PEAR in php?Ans:-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”

58. What is the purpose of the following files having extensions 1) frm 2) MYD 3) MYI. What these files contains?Ans:-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.

27

Page 28: #PHP# Interview Questions

The data file has a `.MYD’ (MYData) extension.The index file has a `.MYI’ (MYIndex) extension,

well i tryed myself to answer most of the questions..and may be u may get more robost answer for these questions..now u can have little idea abt the php frm these answers…and if u hv better answer dan i posted pls email me at [email protected] ( shekhar koli)

72.Nosherwan Adil said,

Q8.How can we extract string ‘abc.com ‘ from a string ‘http://[email protected]’ using regular expression of PHP?

$ext = strrchr(‘http://[email protected]’ , ‘@’ );//output will be abc.com

73.Priya said,

I am really satisfied with the questions and the different answers given.This can be of great help for people looking for a bulk of questions to be asked in interviews.Thankyou

74.Nithin said,

Question 27: What is the functionality of the function strstr and stristr?strstr function used to find first occurrence of a stringex:

stristr function is an Case-insensitive strstrex:

75.jeeva arulraj said,

I am really satisfied with the questions and the different answers given.it will be more useful for people who are seeking php jobs and useful for the interviews.but two many answers make the readers more confusion.Thankyou

76.Archana said,

Answer to Q. 13.

PHP can be executed from Command Line, using the SAP Interface (SAPI) or Server Application Programming Interface named CLI which means Command Line Interface.The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with –enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental

28

Page 29: #PHP# Interview Questions

and the option –enable-cli is on by default. You may use –disable-cli to disable it.

77.parth said,

tell me about Undefined offset when i use do & while loop$count=0;do{echo”The enter Name of your child is”.$_POST[”child”][$count].”";$child_name=$_POST[”child”][$count];//echo $child_name;$count=$count+1;} while($child_name>= 0);where Child[] takenas array

78.Nitesh said,

Q. 3. How can we submit a form without a submit button?

Answer:We can submit a from without a submit button help ho javascript like.

<a href=”void(0)” rel=”nofollow”>Submit Me</a>

79.Nitesh said,

Ans of 3. We can submit a form without a submit button with javascript.

80.Nitesh said,

Ans of 3. We can submit a form without a submit button with the help of javascript.

81.Nitesh said,

Ans of 1: When we submit a form, which has the GET method it pass value in the form of query string (set of name/value pair) and display along with URL. With GET we can a small data submit from the form (a set of 255 character) whereas Post method doesn’t display value with URL. It passes value in the form of Object and we can submit large data from the form.

82.admin said,

R.KaruppaiahTeam LeaderI Tech Indis (p) Ltd Chennai, India.Website: http://www.itechindia.comEmail: [email protected]: 91-9841467284

29

Page 30: #PHP# Interview Questions

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

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

3. 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. For example:

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

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

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

7. How can we extract string ‘abc.com ‘ from a string ‘http://info@a…’ using regular _expression of php?

We can use the preg_match() function with "/.*@(.*)$/" as the regular expression pattern. For example: preg_match("/.*@(.*)$/","http://[email protected]",$data); echo $data[1];

8. How can we create a database using php and mysql?

30

Page 31: #PHP# Interview Questions

PHP: mysql_create_db()Mysql: create database;

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

10. Can we use include ("abc.php") two times in a php page "makeit.php"?

Yes we can include..

11. What are the different tables present in mysql, which type of table is generated when we are creating a table in the followingsyntax: create table employee(eno int(2),ename varchar(10)) ?

Total 5 types of tables we can create

1. MyISAM

2. Heap

3. Merge

4. InnoDB

5. ISAM

6. BDBMyISAM is the default storage engine as of MySQL 3.23.

12. Functions in IMAP, POP3 AND LDAP?

Please visit:http://fi2.php.net/imaphttp://uk2.php.net/ldap

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

14. Suppose your ZEND engine supports the mode Then how can u configure your php ZEND engine to support mode ?

31

Page 32: #PHP# Interview Questions

If you change the line: short_open_tag = off in php.ini file. Then your php ZEND engine support only mode.

15. Shopping cart online validation i.e. how can we configure the paypals?

16. What is meant by nl2br()?

nl2br — Inserts HTML line breaks 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 \n you" to your browser.

17. Draw the architecture of ZEND engine?

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

PHP: php5.1.2MySQL: MySQL 5.1Apache: Apache 2.1

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

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

AES_ENCRYPT () and AES_DECRYPT ()

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

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

32

Page 33: #PHP# Interview Questions

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.

23. What are the differences between PROCEDURE ORIENTED LANGUAGES and OBJECT ORIENTED LANGUAGES?

Traditional programming has the following characteristics:

Functions are written sequentially, so that a change in programming can affect any code that follows it.If a function is used multiple times in a system (i.e., a piece of code that manages the date), it is often simply cut and pasted into each program (i.e., a change log, order function, fulfillment system, etc). If a date change is needed (i.e., Y2K when the code needed to be changed to handle four numerical digits instead of two), all these pieces of code must be found, modified, and tested.Code (sequences of computer instructions) and data (information on which the instructions operates on) are kept separate. Multiple sets of code can access and modify one set of data. One set of code may rely on data in multiple places. Multiple sets of code and data are required to work together. Changes made to any of the code sets and data sets can cause problems through out the system.

Object-Oriented programming takes a radically different approach:

Code and data are merged into one indivisible item – an object (the term "component" has also been used to describe an object.) An object is an abstraction of a set of real-world things (for example, an object may be created around "date") The object would contain all information and functionality for that thing (A dateobject it may contain labels like January, February, Tuesday, Wednesday. It may contain functionality that manages leap years, determines if it is a business day or a holiday, etc., See Fig. 1). Ideally, information about a particular thing should reside in only one place in a system. The information within an object is encapsulated (or hidden) from the rest of the system.A system is composed of multiple objects (i.e., date function, reports, order processing, etc., See Fig 2). When one object needs information from another object, a request is sent asking for specific information. (for example, a report object may need to know what today’s date is and will send a request to the date object) These requests are called messages and each object has an interface that manages messages.OO programming languages include features such as "class", "instance", "inheritance", and "polymorphism" that increase the power and flexibility of an object.

24. What is the use of friend function?

Friend functionsSometimes 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 whichnames them as a friend, as if they were themselves members of that class.

33

Page 34: #PHP# Interview Questions

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.

class mylinkage{private:mylinkage * prev;mylinkage * next;

protected:friend void set_prev(mylinkage* L, mylinkage* N);void set_next(mylinkage* L);

public:mylinkage * succ();mylinkage * pred();mylinkage();};

void mylinkage::set_next(mylinkage* L) { next = L; }

void set_prev(mylinkage * L, mylinkage * N ) { N->prev = L; }

Friends in other classes

It is possible to specify a member function of another class as a friend as follows:

class C{friend int B::f1();};class B{int f1();};

It is also possible to specify all the functions in another class as friends, by specifying the entire class as a friend.

class A{friend class B;};

Friend functions allow binary operators to be defined which combine private data in a pair of objects. This is particularly powerful when using the operator overloading features of C++. We will return to it when we look at overloading.

25. What are the differences between public, private, protected, static, transient, final and volatile?element Class Interface

34

Page 35: #PHP# Interview Questions

Data field Method Constructormodifier top level nested top level nested(outer) (inner) (outer) (inner)final yes yes no yes yes no noprivate yes yes yes no yes no yesprotected yes yes yes no yes no yespublic yes yes yes yes yes yes yesstatic yes yes no no yes no yestransient yes no no no no no novolatile yes no no no no no no

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

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 behaviour is to display them to the user when they take place.

27. What is the functionality of the function strstr and stristr?

strstr() returns part of a given string from the first occurrence of a given substring to the end of the string. For example: strstr("[email protected]","@") will return "@example.com".stristr() is idential to strstr() except that it is case insensitive.

28. What are the differences between PHP 3 and PHP 4 and PHP 5?

Go read the release notes at http://php.net.

29. How can we convert asp pages to php pages?

You can download asp2php front-end application from the site http://asp2php.naken.cc.

30. What is the functionality of the function htmlentities? Answer: htmlentities — Convert all applicable characters to HTML entitiesThis function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

31. How can we get second of the current time using date function?

35

Page 36: #PHP# Interview Questions

$second = date("s");

32. How can we convert the time zones using php?

33. 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.urldecode() returns the URL decoded version of the given string.

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

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

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

We can use the session_register ($ur_session_var) function.

36. 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 () functionTo know the Image size use getimagesize () functionTo know the image width use imagesx () functionTo know the image height use imagesy() function

37. How can we get the browser properties using php?

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

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

40. How can we take a backup of a mysql table and how can we restore it.?Answer: Create a full backup of your database: shell> mysqldump –tab=/path/to/some/dir –opt db_name Or: shell> mysqlhotcopy db_name /path/to/some/dirThe full backup file is just a set of SQL statements, so restoring it is very easy:

shell> mysql "."Executed";mysql_close($link2);

53. List out the predefined classes in php?

36

Page 37: #PHP# Interview Questions

DirectorystdClass__PHP_Incomplete_Classexceptionphp_user_filter

54. How can I make a script that can be bilanguage (supports Eglish, German)?

You can change charset variable in above line in the script to support bilanguage.

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

56. How can we send mail-using JavaScript?

NO! JavaScript can't email a form! but, there are alternatives to send the form data to an email address.

57. How can we repair a mysql table?

The syntex for repairing a mysql table isREPAIR 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

58. What are the advantages of stored procedures, triggers, indexes?

A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep re-issuing the entire query but can refer to the stored procedure. This provides better overall performance because the query has to be parsed only once, and less information needs to be sent between the server and the client. You can also raise the conceptual level by having libraries of functions in the server. However, stored procedures of course do increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of stored procedure, one that is invoked when a particular event occurs. For example, you can install a stored procedure that is triggered each time a record is deleted from a transaction table and that stored procedure automatically deletes the corresponding customer from a customer table when all his transactions are deleted.

37

Page 38: #PHP# Interview Questions

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.

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

Database name- 64Table name -64Fieldname-64

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

61. What are the other commands to know the structure of table using mysql commands except explain command?

describe table_name;

62. How many tables will create when we create table, what are they?

3 tables will create when we create table. They areThe '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension,

63. What is the purpose of the following files having extensions 1) frm 2) MYD 3) MYI. What these files contains?

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,

64. What is maximum size of a database in mysql?

If the operating system or filesystem places a limit on the number of files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in a directory can place a practical limit on the 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

38

Page 39: #PHP# Interview Questions

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) 4TBSolaris 9/10 16TBNetWare w/NSS filesystem 8TBWin32 w/ FAT/FAT32 2GB/4GBWin32 w/ NTFS 2TB (possibly larger)MacOS X w/ HFS+ 2TB

65. Give the syntax of Grant and Revoke commands?The generic syntax for grant is as following> GRANT [rights] on [database/s] TO [username@hostname] IDENTIFIED BY [password]now rights can bea) All privilegesb) combination of create, drop, select, insert, update and delete etc.

We can grant rights on all databse by using *.* or some specific database by database.* or a specific table by database.table_nameusername@hotsname can be either username@localhost, username@hostname and username@%where hostname is any valid hostname and % represents any name, the *.* any conditionpassword is simply the password of user

The generic syntax for revoke is as following> REVOKE [rights] on [database/s] FROM [username@hostname]now rights can be as explained abovea) All privilegesb) combination of create, drop, select, insert, update and delete etc.username@hotsname can be either username@localhost, username@hostname and username@%where hostname is any valid hostname and % represents any name, the *.* any condition

66. Explain Normalization concept?

The normalization process involves getting our data to conform to three progressive normal forms, and a higher level of normalization cannot be achieved until the previous levels have been achieved (there are actually five normal forms, but the last two are mainly academic and will not be discussed).

39

Page 40: #PHP# Interview Questions

First Normal Form

The First Normal Form (or 1NF) involves removal of redundant data from horizontal rows. We want to ensure that there is no duplication of data in a given row, and that every column stores the least amount of information possible (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 Normal Form.

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 dependant on the primary key, but dependant on another value in the table

67. How can we find the number of rows in a table using mysql?

Answer: Use this for mysql>SELECT COUNT(*) FROM table_name;but if u r particular about no of rows with some special resultdo this>SELECT [colms],COUNT(*) FROM table_name [where u put conditions];

68. How can we find the number of rows in a result set using php?

Answer: for PHP

$result = mysql_query($any_valid_sql, $database_link);$num_rows = mysql_num_rows($result);echo "$num_rows rows found";

69. How many ways we can we find the current date using mysql?

SELECT CURDATE();CURRENT_DATE() = CURDATE()for time useSELECT CURTIME();CURRENT_TIME() = CURTIME()

70. What are the advantages and disadvantages of CASCADE STYLE SHEETS?

External Style Sheets

Advantages

40

Page 41: #PHP# Interview Questions

Can control styles for multiple documents at onceClasses can be created for use on multiple HTML element types in many documentsSelector and grouping methods can be used to apply styles under complex contexts

Disadvantages

An extra download is required to import style information for each documentThe rendering of the document may be delayed until the external style sheet is loadedBecomes slightly unwieldy for small quantities of style definitions

Embedded Style Sheets

Advantages

Classes can be created for use on multiple tag types in the documentSelector and grouping methods can be used to apply styles under complex contextsNo 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 definitionsCan 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 onceAuthor can not create or control classes of elements to control multiple element types within the documentSelector grouping methods can not be used to create complex element addressing scenarios

71. What type of inheritance that php supports? Answer: In PHP an extended class is always dependent on a single base class, that is, multiple inheritance is not supported. Classes are extended using the keyword 'extends'.

72. How can increase the performance of mysql select query?

The structure of table view buyers is as follows+—————-+————-+——+—–+———+—————-+| Field | Type | Null | Key | Default | Extra |

41

Page 42: #PHP# Interview Questions

+—————-+————-+——+—–+———+—————-+| user_pri_id | int(15) | | PRI | NULL | auto_increment || userid | varchar(10) | YES | | NULL | |+—————-+————-+——+—–+———+—————-+the value of user_pri_id the last row 2345 then What will happen inthe following conditions

Condition1: Delete all the rows and insert another row then What is the starting value for this auto incremented field user_pri_id ,Condition2: Delete the last row(having the field value 2345) and insert another row then What is the value for this auto incremented field user_pri_id

In general, when you want to make a slow SELECT … WHERE query faster, the first thing to check is whether you can add an index. All references between different tables should usually be done with indexes. You can use the EXPLAIN statement to determine which indexes are used for a SELECT. See section 7.4.5 How MySQL Uses Indexes and section 7.2.1 EXPLAIN Syntax (Get Information About a SELECT).Some general tips for speeding up queries on MyISAM tables:

To help MySQL optimize queries better, use ANALYZE TABLE or run myisamchk –analyze on a table after it has been loaded with data. This updates a value for each index part that indicates the average number of rows that have the same value. (For unique indexes, this is always 1.) MySQL will use this to decide which index to choose when you join two tables based on a non-constant expression. You can check the result from the table analysis by using SHOW INDEX FROM tbl_name and examining the Cardinality value. myisamchk –description –verbose shows index distribution information.

To sort an index and data according to an index, use myisamchk –sort-index –sort-records=1 (if you want to sort on index 1). This is a good way to make queries faster if you have a unique index from which you want to read all records in order according to the index. Note that the first time you sort a large table this way, it may take a long time.

In both cases let the value for auto increment field be n then next row will have value n+1 i.e. 2346

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

74. What is the difference between GROUP BY and ORDER BY in Sql?

To sort a result, use an ORDER BY clause.

The most general way to satisfy a GROUP BY clause is to scan the whole table and create a new temporary table where all rows from each group are consecutive, and then use this temporary table to discover groups and apply aggregate functions (if any).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

42

Page 43: #PHP# Interview Questions

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

75. What is the difference between char and varchar data types?

char(M) M bytes 0

80. How can we change the name of a column of a table?

MySQL query to rename table: RENAME TABLE tbl_name TO new_tbl_name[, tbl_name2 TO new_tbl_name2] …or,ALTER TABLE tableName CHANGE OldName newName.

81. How can we change the name and data type of a column of a table?

ALTER [IGNORE] TABLE tbl_namealter_specification [, alter_specification] | CHANGE [COLUMN] old_col_name column_definition[FIRST|AFTER col_name]

82. What are the differences between drop a table and truncate a table?Answer: Delete a Table or DatabaseTo delete a table (the table structure, attributes, and indexes will also be deleted).What if we only want to get rid of the data inside a table, and not the table itself? Use the TRUNCATE TABLE command (deletes only the data inside the table).

83. When you want to show some part of a text displayed on an HTML page in red font color, what different possibilities are there to do this? What are the advantages/disadvantages of these methods?

Using Html font color tag:I am AminUsing tag in CSS:STRONG {color:red}So when we use the tag:I am Amin about this.Using Class in CSS:

.colorclass{color:#FF3399;font-weight:900;}

I am AminIf we use html the modification will be trouble some because we have to change the code of the page. But when we use CSS then it will be easy to change the CSS file and we can get the desired out put.

43

Page 44: #PHP# Interview Questions

84. When viewing an HTML page in a Browser, the Browser often keeps this page in its cache. What can be possible advantages/disadvantages of page caching? How can you prevent caching of a certain page (please give several alternate solutions)?

When you use the metatag in the header section at the beginning of an HTML Web page, the Web page may still be cached in the Temporary Internet Files folder.

A page that Internet Explorer is browsing is not cached until half of the 64 KB buffer is filled. Usually, metatags are inserted in the header section of an HTML document, which appears at the beginning of the document. When the HTML code is parsed, it is read from top to bottom. When the metatag is read, Internet Explorer looks for the existence of the page in cache at that exact moment. If it is there, it is removed. To properly prevent the Web page from appearing in the cache, place another header section at the end of the HTML ocument. For example:

85. What are the different methods of passing data or information between two calls of a web page? What are the advantages/disadvantages of these methods?

86. An Apache web server is running on a Linux system. Suddenly, the web server delivers the pages very slow. How could you find out possible reasons for that (when using system commands, please specify their names)?

87. What are the different ways to login to a remote server? Explain the means, advantages and disadvantages?

There is at least 3 ways to logon to a remote server:Use ssh or telnet if you concern with securityYou can also use rlogin to logon to a remote server.

88. Please give a regular _expression (preferably Perl/PREG style), which can be used to identify the URL from within a HTML link tag. Example: The regular _expression should match the tag mysqldump -u user -ppassword –opt -full database_name > backupfile.sqlThen move the resulting file(s) to your preferred backup areas. If you require more information on the mysqldump command, then simply check out this URL:www.mysql.com/documentation/mysqlCopy all the relevant table files.

If the server isn't updating anything (or you've deliberately killed mysqld for this purpose) then you can copy all the files with the following extensions in your MySQL data directory:*.frm*.myd*.myiMake sure you restart the MySQL daemon once you finish copying and downloading the files to your preferred backup areas.TIP: once you've completed the backup, restart MySQL with the –log-update switch. This will allow you to keep track of all modifications done in the MySQL tables since your last 'dump'.To restore your dumps, you should either restore to an existing database or

44

Page 45: #PHP# Interview Questions

create a new database usingshell> mysqladmin create database_namethen issue the following command :shell> mysql -u user -ppassword database_name

94. What is meant by MIME?

Multipurpose Internet Mail Extensions.WWW's 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. …

95. 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 usersA system for code distribution and package maintenanceA standard style for code written in PHPThe PHP Foundation Classes (PFC),The PHP Extension Community Library (PECL),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.http://pear.php.net/manual/en/introduction.php

96. How can I use the COM components in php?

The COM class provides a framework to integrate (D)COM components into your PHP scripts.string COM::COM ( string module_name [, string server_name [, int codepage]])COM class constructor. Parameters:module_namename or class-id of the requested component.server_namename of the DCOM server from which the component should be fetched. If NULL, localhost is assumed. To allow DCOM com.allow_dcom has to be set to TRUE in php.ini.codepagespecifies the codepage that is used to convert php-strings to unicode-strings and vice versa. Possible values are CP_ACP, CP_MACCP, CP_OEMCP, CP_SYMBOL, CP_THREAD_ACP, CP_UTF7 and CP_UTF8.Usage:Version}\n"; //bring it to front $word->Visible = 1; //open an empty document $word->Documents->Add(); //do some weird stuff $word->Selection->TypeText("This is a test…"); $word->Documents[1]->SaveAs("Useless test.doc"); //closing word $word->Quit(); //free the object $word->Release(); $word = null; ?>

45

Page 46: #PHP# Interview Questions

97. How can I load the dlla€™s dynamically?

98. How many ways we can give the output to a browser?

HTML outputPHP, ASP, JSP, Servlet FunctionScript Language output FunctionDifferent Type of embedded Package to output to a browser

99. How can we know that a session is started or not?

a session starts by session_start()function.this session_start() is always declared in header portion.it always declares first.then we write session_register().

100. What is the default session time in php and how can I change it?

The default session time in php is until closing of browser

101. What changes I have to done in php.ini file for file uploading?

Make the following Line uncomment like:; Whether to allow HTTP file uploads.file_uploads = On; Temporary directory for HTTP uploaded files (will use system default if not; specified).upload_tmp_dir = C:\apache2triad\temp; Maximum allowed size for uploaded files.upload_max_filesize = 2M

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

103. How can I set a cron and how can I execute it in Unix, Linux, and windows?

Cron is very simply a Linux module that allows you to run commands at predetermined times or intervals. In Windows, it’s called Scheduled Tasks. The name Cron is in fact derived from the same word from which we get the word chronology, which means order of time.The easiest way to use crontab is via the crontab command.# crontab –eThis command ‘edits’ the crontab. Upon employing this command, you will be

46

Page 47: #PHP# Interview Questions

able to enter the commands that you wish to run. My version of Linux uses the text editor vi. You can find information on using vi here.The syntax of this file is very important – if you get it wrong, your crontab will not function properly. The syntax of the file should be as follows:minutes hours day_of_month month day_of_week commandAll the variables, with the exception of the command itself, are numerical constants. In addition to an asterisk (*), which is a wildcard that allows any value, the ranges permitted for each field are as follows:Minutes: 0-59Hours: 0-23Day_of_month: 1-31Month: 1-12Weekday: 0-6We can also include multiple values for each entry, simply by separating each value with a comma.command can be any shell command and, as we will see momentarily, can also be used to execute a Web document such as a PHP file.So, if we want to run a script every Tuesday morning at 8:15 AM, our mycronjob file will contain the following content on a single line:15 8 * * 2 /path/to/scriptnameThis all seems simple enough, right? Not so fast! If you try to run a PHP script in this manner, nothing will happen (barring very special configurations that have PHP compiled as an executable, as opposed to an Apache module). The reason is that, in order for PHP to be parsed, it needs to be passed through Apache. In other words, the page needs to be called via a browser or other means of retrieving Web content.For our purposes, I’ll assume that your server configuration includes wget, as is the case with most default configurations. To test your configuration, log in to shell. If you’re using an RPM-based system (e.g. Redhat or Mandrake), type the following:# wget –helpIf you are greeted with a wget package identification, it is installed in your system.You could execute the PHP by invoking wget on the URL to the page, like so:# wget http://www.example.com/file.phpNow, let’s go back to the mailstock.php file we created in the first part of this article. We saved it in our document root, so it should be accessible via the Internet. Remember that we wanted it to run at 4PM Eastern time, and send you your precious closing bell report? Since I’m located in the Eastern timezone, we can go ahead and set up our crontab to use 4:00, but if you live elsewhere, you might have to compensate for the time difference when setting this value.This is what my crontab will look like:0 4 * * 1,2,3,4,5 wget http://www.example.com/mailstock.php

104. Steps for the payment gateway processing?

An online payment gateway is the interface between your merchant account and your Web site. The online payment gateway allows you to immediately verify credit card transactions and authorize funds on a customer’s credit card directly from your Web site. It then passes the transaction off to your merchant bank for processing, commonly referred to as transaction batching

105. How many ways I can register the variables into session?

47

Page 48: #PHP# Interview Questions

session_register(); $_SESSION[]; $HTTP_SESSION_VARS[];

106. Explain different types of errors in php (i.e. arguments in error reporting function)?

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

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 behaviour is to display them to the user when they take place.

107. How many ways I can redirect a php page?

Here are the possible ways of php page redirection.Using Java script:'; echo 'window.location.href="'.$filename.'";'; echo ''; echo ''; echo ''; echo ''; } } redirect('http://maosjb.com'); ?>Using php function:Header("Location:http://maosjb.com ");

108. List out different arguments in php header function?

void header ( string string [, bool replace [, int http_response_code]])

109. What type of headers have to add in the mail function in which file a attached?

$boundary = '—–=' . md5( uniqid ( rand() ) );$headers = "From: \"Me\"\n";$headers .= "MIME-Version: 1.0\n";$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"";

110. What is the difference between and And which can be preferable?

move_uploaded_file ( string filename, string destination)

This function checks to ensure that the file designated by filename is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by destination.

48

Page 49: #PHP# Interview Questions

If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.

If filename is a valid upload file, but cannot be moved for some reason, no action will occur, and move_uploaded_file() will return FALSE. Additionally, a warning will be issued.

116. What is the difference between Reply-to and Return-path in the headers of a mail function?

Reply-to: Reply-to is where to delivery the reply of the mail.

Return-path: Return path is when there is a mail delivery failure occurs then where to delivery the failure notification.

117. Explain about Type Juggling in php?

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which that variable is used. That is to say, if you assign a string value to variable $var, $var becomes a string. If you then assign an integer value to $var, it becomes an integer.An example of PHP's automatic type conversion is the addition operator '+'. If any of the operands is a float, then all operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does NOT change the types of the operands themselves; the only change is in how the operands are evaluated.

$foo += 2; // $foo is now an integer (2)$foo = $foo + 1.3; // $foo is now a float (3.3)$foo = 5 + "10 Little Piggies"; // $foo is integer (15)$foo = 5 + "10 Small Pigs"; // $foo is integer (15)

If the last two examples above seem odd, see String conversion to numbers.If you wish to change the type of a variable, see settype().If you would like to test any of the examples in this section, you can use the var_dump() function.Note: The behavior of an automatic conversion to array is currently undefined.

Since PHP (for historical reasons) supports indexing into strings via offsets using the same syntax as array indexing, the example above leads to a problem: should $a become an array with its first element being "f", or should "f" become the first character of the string $a?The current versions of PHP interpret the second assignment as a string offset identification, so $a becomes "f", the result of this automatic conversion however should be considered undefined. PHP 4 introduced the new curly bracket syntax to access characters in string, use this syntax instead of the one presented above:

118. How can I get the only name of the current executing file?

49

Page 50: #PHP# Interview Questions

119. How can I embed a java programme in php file and what changeshave to be done in php.ini file?

There are two possible ways to bridge PHP and Java: you can either integrate PHP into a Java Servlet environment, which is the more stable and efficient solution, or integrate Java support into PHP. The former is provided by a SAPI module that interfaces with the Servlet server, the latter by this Java extension.The Java extension provides a simple and effective means for creating and invoking methods on Java objects from PHP. The JVM is created using JNI, and everything runs in-process.

Example Code:

getProperty('java.version') . ''; echo 'Java vendor=' . $system->getProperty('java.vendor') . ''; echo 'OS=' . $system->getProperty('os.name') . ' ' . $system->getProperty('os.version') . ' on ' . $system->getProperty('os.arch') . ' '; // java.util.Date example $formatter = new Java('java.text.SimpleDateFormat', "EEEE, MMMM dd, yyyy 'at' h:mm:ss a zzzz"); echo $formatter->format(new Java('java.util.Date')); ?>

The behaviour of these functions is affected by settings in php.ini.Table 1. Java configuration optionsNameDefaultChangeablejava.class.pathNULLPHP_INI_ALLName Default Changeablejava.homeNULLPHP_INI_ALLjava.library.pathNULLPHP_INI_ALLjava.libraryJAVALIBPHP_INI_ALL

120. How can I find what type of images that the php version supports?

Using Imagetypes() function we can knowUsage:

121. The table tbl_sites contains the following data.—————————————————–Userid sitename country——————————————————1 sureshbabu indian2 phpprogrammer andhra3 php.net usa4 phptalk.com germany5 mysql.com usa

50

Page 51: #PHP# Interview Questions

6 sureshbabu canada7 phpbuddy.com pakistan8. phptalk.com austria9. phpfreaks.com sourthafrica10. phpsupport.net russia11. sureshbabu australia12. sureshbabu nepal13. phptalk.com italy

Write a select query that will displayed the duplicated site name and how many times it is duplicated?

SELECT sitename,COUNT(sitename) AS NumOccurrencesFROM tbl_sitesGROUP BY sitemailHAVING ( COUNT(sitemail) > 1 )OrSELECT sitenameFROM tbl_sitesGROUP BY sitenameHAVING ( COUNT(sitename) = 1 )

122. How can we send mail using JavaScript?

No. You can't send mail using Javascript. But you can execute a client side email client to send the email using mailto: code.Using clientside email client

function myfunction(form){tdata=document.myform.tbox1.value;location="mailto:[email protected]?subject="+tdata+"/MYFORM";return true; }}

83.Tejas vadalia said,

Answer For Q.6 can be found athttp://www.phpbuilder.com/manual/en/language.variables.variable.php

84.hita said,

Answer for Q.No:7

echo strstr(”[email protected]”,”abc”);

85.hita said,

Answer of Q.No:48

count(array) or sizeof(array)

51

Page 52: #PHP# Interview Questions

86.Sajeesh Francis said,

Answer for Q.No:7

$data = “http://[email protected]”;$pattern = “/[A-Z0-9.-]+\.[A-Z]{2,4}\b/i”;

if(preg_match($pattern, $data, $matches)){echo $matches[0];} else {echo “A match was not found.”;}

87.Rahul Chahwala said,

25. 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 a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.

88.Rahul Chahwala said,

Answer to que 7

Use the strrchr function.strrchr(”http://[email protected]”, “a” )//outputabc.com

89.Rahul Chahwala said,

Answer to question 16

nl2br():Inserts HTML line breaks lines in a string.Example:echo (”What a nice \n day”);//outputWhat a nice day.

echo nl2br(”What a nice \n day”);//outputWhat a niceday

52

Page 53: #PHP# Interview Questions

90.Arghadip Acharya said,

Answer of Question Number 1:

This is not the only answer between GET & POST method posted by Mr.Cahndu.Ther are another differences:Using GET method, only 255 datas can be submitted (For some browser it exceeds to 4kb), but, POST method has no such restriction.GET method is used for the creation of search engines, where inserion or modification of data is not required. This is good practice of codeing.POST method is used when the insertion or modification of data in database is required.

Thank You.

91.nilanjan karmakar said,

function test(){alert(”abc”);document.form1.action=’test1.php’;document.form1.submit();}

92.nilanjan karmakar (question:8) said,

CREATE TABLE `test` (`id` INT( 10 ) NOT NULL ,`ss` VARCHAR( 122 ) NOT NULL ,`sa` VARCHAR( 122 ) NOT NULL);

93.shiva.G said,

How can we swap two varaibles without using any intermediate variable?

94.Kiran said,

Correction for the 11 the Question of PHP interview questions————————————————————-# If the variable $a is equal to 5 and variable $b is equal to character a, what’s the value of $$b? -100, it’s a reference to existing variable.

Correction———-$$b=$a Where as the value of $a=5;so the Actual answer is 5.

95.appsaheb bagali said,

53

Page 54: #PHP# Interview Questions

Q no 1)

1. GET method have limination to transper the data as compare to POST2. GET method data will show in the URL POST method data will pass through Header Body3. In file uplaod you must use the POST Method GET will not work4. In Search engine yahoo Google will use the GET methods because GET Method datawill store in server logs of Apache. from they can keep track of the Frequentlly searched data

96.Romi said,

37. How can we get the browser properties using PHP?Ans: Use function get_browser to get all the properties of the browser.$browser = get_browser(null, true);print_r($browser);

97.Tanvir Ahmad said,

Answer of Question no 21In PHP you can generate hashes using the md5() and sha1 functions. md5() returns a 128-bit hash (32 hexadecimal characters), whereas sha1() returns a 160-bit hash (40 hexadecimal characters). For example:

This code will output the following:

Original string: PHP & Information SecurityMD5 hash: 88dd8f282721af2c704e238e7f338c41SHA-1 hash: b47210605096b9aa0129f88695e229ce309dd362

–In MySQL you can generate hashes internally using the password(), md5(), or sha1 functions. password() is the function used for MySQL’s own user authentication system. It returns a 16-byte string for MySQL versions prior to 4.1, and a 41-byte string (based on a double SHA-1 hash) for versions 4.1 and up. md5() is available from MySQL version 3.23.2 and sha1() was added later in 4.0.2.

mysql> select PASSWORD( ‘PHP & Information Security’ );

98.Nilay Anand said,

I do dislike questions that require one to have memorized functions and parameter orders. I always prefer people to prove what they know, rather than what they don’t know.The all above question need one to memorized PHP in depth.

99.Rakesh Chandel said,

what function is used to free the resultset in php?what is the difference in trim() and chop()?

54

Page 55: #PHP# Interview Questions

100. rishi said,

answer:How can we swap two varaibles without using any intermediate variable?x and y are variablesstep 1: x=x+ystep 2: y=x-ystep 3: x=x-y

101. Amol Bhavsar said,

Answer for Question 3 :You can submit form without Submit Button in Two ways :(1).Using images(2).Using Javascript : You can submit form using Javascript by first defining first functions and calling them on some events like “onClick”,”onBlur” etc.

102. Amol Bhavsar ,Pune (PHP Developer) said,

Answer to question 1 :Main differences between GET & POST methods are :-GET method is the default method for forms.-In the form posted with GET method , the passed variables and their values are shown in address bar.-Therefore ,GET method is useful to BookMark an URL.-But’also there is limit on length of values of form elments passed.-GET method is not secure as navigated values are displayed in address bar.-Get method is not recommonded in applications where user information security is required.

-POST method does not display any content in the address bar so,complete bookmarking is not possible as that of GET method .-With the POST method ,there is no limit on amount of data POSTED.-POST method is recommonded where ,there is issue of user-information security.-POST method is

103. Niladri said,

Any one tell me what is outer - joining in mysql?

104. Niladri said,

what is the difference between split() and explode() ?

105. Niladri said,

What is the utility of GD Library ?

106. Hitu Patel said,

49). What is the difference between ereg_replace() and eregi_replace()?

55

Page 56: #PHP# Interview Questions

eregi_replace — replace regular expression case insensitiveereg_replace — replace regular expression

107. Hitu Patel said,

(3) .How can we submit a form without a submit button?

(1) we can use the document.form.submit() function of javascript for submit the form.

108. Hitu Patel said,

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

109. Hitu Patel said,

(20). You can use the AES functions to store data in an encrypted form by modifying your queries:

INSERT INTO t VALUES (1,AES_ENCRYPT(’text’,'password’));

For Decriyption use AES_DECRYPT()

110. Sumanta said,

How can we extract string ‘abc.com ‘ from a string ‘http://[email protected]’ using regular expression of PHP?

Ans is: $url = http://[email protected];$domain = strstr($url, ‘@’, 1);echo $domain;

It will print abc.com.

111. Sumanta said,

Sorry for last comment.The actual answer is following:–

$url = http://[email protected];$domain = strstr($url, ‘a’);echo $domain;

It will print abc.com.

112. Manokaran said,

Difference between Session and Cookie in PHP ?

Session variables are stored in Server system.

56

Page 57: #PHP# Interview Questions

Cookie variables are stored in Client system.

57