34984194 25524375 php interview questions

59
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 th e 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 t he father of PHP and exp lain the c hange s in PHP versions? 3. How can we submit a form with out a su bmit button? 4. In how man y ways we can r etrieve the date in the result set of mysql using PHP? 5. What is the diff erenc e between my sql_f etch_ objec t and mysql_ fetch _array ? 6. What is the difference bet ween $ message and $$message? 7. How can we ext ract st ring ‘techinterviews.com ‘ from a string  ‘http://www.tec hinterviews.com’ using regular expression of PHP? 8. How can we create a database us ing PHP and mysql ? 9. What are th e 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 my sql, 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, POP 3 AND LDAP? 13. How can I execute a PH P script using comman d 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 c an we configure Paypal, etc.? 16. What is meant by nl2br()? 17.Draw the architecture of Zend en gine? 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 usin g PHP? 22. What are the features and advantages of obj ect-oriented programming? 23. What are the differences between procedure-oriented languages and object- oriented languages? 24. What is the use of friend func tion? 25. What are the differences between p ublic, private, protected, static, trans ient, final and volatile? 26. What are the different types of err ors in PHP? 27. What is the functionality of the func tion strstr and stristr? 28. What are the differences between P HP 3 and PHP 4 and PHP 5? 29. How can we conver t asp pages to PHP pages? 30. What is the functionality of the func tion htmlentities? 31. How can we get second of the current time using date function? 32. How can we conver t the time zones using PHP ? 33. What is meant by urlencode and url docode? 34. What is the difference between th e functions unlink and unset? 1

Upload: vamshi-krishna

Post on 29-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 1/59

PHP interview questions, Part 1

Web dev interview questions

Feel free to post the answers and discuss the questions in the comments. MizanurRahman 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 isgenerated when we are creating a table in the following syntax: create tableemployee(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 operatingsystems?

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?

1

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 2/59

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

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 canonly access the data by the field names, and not by their offsets (numbersare illegal property names).

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

chandu said,

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

chandu said,

Answer to Q7)

2

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 3/59

$exploded[1] should have abc.com

chandu said,

answer to Q8)mysql_create_db() should work

chandu said,

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

chandu said,

answer to q10) Yes we can include that many times we want, but here aresome 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 befunctions or classes or variables with the same name in abc.PHP andmakeit.php

chandu said,

correction to my previous comment:I’v specified functions,classes and variables, exactly what I meant withvariables is…u’v to

make sure that the variables wont over write each other.

chandu said,

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

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

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

meenakshi said,

3

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 4/59

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

sukhbir said,

ans_16

nl2br() inserts html in string

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

outputgod blessyou

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 byurl. Post method doesn’t display these values.

D R Jadav said,

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

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 canonly access the data by the field names, and not by their offsets (numbersare illegal property names). Note: Field names returned by this function arecase-sensitive.field; /* this is invalid */echo $row->0;

?>

D R Jadav said,

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

4

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 5/59

is equivalent to

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

D R Jadav said,

Answer of Question 7 :

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

D R Jadav said,

Answer of Question no 8 :

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

D R Jadav said,

Answer of Question no 9 :

The include_once() statement includes and evaluates the specified file duringthe 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 hasalready been included, it will not be included again. The major differencebetween include() and require() is that in failure include produces a warningmessage whereas require produces a Fatal errors.

D R Jadav said,

Answer of Question no 10 :

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

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)

5

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 6/59

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

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. Bydefault location of php parser is /var/www/html so set the path of thisdirectory and just use as following#php sample.php

D R Jadav said,

Answer of Question no 16 :

Returns string with ” inserted before all newlines

D R Jadav said,

Answer of Question no 18 :

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

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

D R Jadav said,

Answer of Question no 21 :

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

D R Jadav said,

Answer of Question no 26 :

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

errors.

D R Jadav said,

Answer of Question no 27 :

string strstr ( string str1, string str2) this function search the string str1 forthe first occurrence of the string str2 and returns the part of the string str1

6

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 7/59

from the first occurrence of the string str2. This function is case-sensitive andfor case-insensitive search use stristr() function.

D R Jadav said,

Answer of Question no 29 :

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

Praveen said,

nl2br(PHP 3, PHP 4 )

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

Grant Harding said,

Is it really in the best interest of both employers and job-seekers to have theanswers 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.

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;

}

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

7

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 8/59

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

b.stdClass

2.Ming Defined Classes

These classes are defined in the Ming extension, and will only be availablewhen that extension has either been compiled into PHP or dynamically loadedat 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

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

a. OCI-Lobb. OCI-Collection

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

a. QDomDocument

8

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 9/59

b. QDomNode

Bharati Raul said,

1) What are the differences between Get and postmethods in form submitting, give the case where we can

use 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” 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 button

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

9

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 10/59

(numbers are illegal property names).————————————————–

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

————————————————–

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

page “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.————————————————–

Kumar said,

10

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 11/59

What is meant by urlencode and urldocode?string urlencode(str)where str contains a string like this “hello world” and the return value will beURL encoded and can be use to append with URLs, normaly used to appneddata 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” 

Kumar said,

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

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

Kumar said,

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

Kumar said,

How can we know the count/number of elements of an array?2 ways

a) sizeof($urarray) This function is an alias of count()b) count($urarray)interestingly if u just pass a simple var instead of a an array it will return 1.

ramesh said,

Q 20;

AES_ENCRYPT() and AES_DECRYPT()

Mikhail Esteves said,

Question 56: This question is wrong. You aren’t really ’sending mail’ whendoing 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.

Pujitha Sendanayake said,

some information about zend engine.

11

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 12/59

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

Pujitha Sendanayake said,

Q46-

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

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

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

Rahul Amrutkar said,

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

Rahul Amrutkar said,

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

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 > 0identical 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 involveanything, 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

12

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 13/59

latter means that the form data is to appear within a message body. For GETin 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 OFMYSQL USING PHP?

mysql_fetch_array — Fetch a result row as an associative array, a numericarray, 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

5.WHAT IS THE DIFFERENCE BETWEEN MYSQL_FETCH_OBJECT ANDMYSQL_FETCH_ARRAY?

mysql_fetch_array — Fetch a result row as an associative ARRAY, a numericarray, 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”;}

13

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 14/59

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 thaninclude().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 duringthe 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 hasalready been included, it will not be included again. It des not call a fatal errorif file not exists. require_once() does the same as include_once(), but it callsa 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 OFTABLE IS GENERATED WHEN WE ARE CREATING A TABLE IN THE FOLLOWINGSYNTAX: CREATE TABLE EMPLOYEE(ENO INT(2),ENAME VARCHAR(10)) ?

MyISAM: This is default. Based on Indexed Sequntial Access Method. Theabove SQL will create a MyISA table.ISAM : sameHEAP : Fast data access, but will loose data if there is a crash. Cannot haveBLOB, 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 ApplicationProgramming Interface) named CLI which means Command Line Interface.

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

Its already supported.

15. WHAT IS MEANT BY NL2BR()?

14

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 15/59

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 16/59

htmlspecialchars : Convert some special characters to HTML entities (Only themost 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 digitsand spaces encoded as plus (+) signs.

urldocode : Decodes URL-encoded string

23. WHAT IS THE DIFFERENCE BETWEEN THE FUNCTIONS UNLINK ANDUNSET?

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) OFAN IMAGE USING PHP IMAGE FUNCTIONS?

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

imagesy — 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 WERESTORE IT. ?

16

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 17/59

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 fortransferring the data to another SQL server (not necessarily a MySQL server).The dump will contain SQL statements to create the table and/or populate thetable.-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 justwant to get a dump of the structure for a table!

29. OPTIMISING QUERIES

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

30. COOKIES

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

variable - name of the cookie variable

variable - value of the cookie variabletime - 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() ANDEREGI_REPLACE()?

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

17

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 18/59

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

matts said,

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

mahesh said,

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

u24 said,

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

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, thescript returns a fatal error. The default limit is 30 seconds or, if it exists, themax_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 otherwords, if the timeout is the default 30 seconds, and 25 seconds into scriptexecution a call such as set_time_limit(20) is made, the script will run for atotal of 45 seconds before timing out.

18

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 19/59

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 versionsbefore 4.0.5 will return string with ” inserted before newlines instead of ”.

Example 1. using nl2br()

this will output :

foo isn’tbar

Subir said,

Ans (14)

In php.ini file:

set

short_open_tag=on

to make PHP support

parmanand said,

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

Viral Hirpara said,

Question No. 7

Answer,

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

19

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 20/59

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

Arvind said,

For Q#1

What are "Get" and "Post"?

Get and Post are methods used to send data to the server: With the Getmethod, the browser appends the data onto the URL. With the Post method,the data is sent as "standard input."Major Difference

In simple words, in POST method data is sent by standered input(nothing

shown in url when posting while in GET method data is sent throughquery 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 similar

action to post the form values are sent through ‘visible’ query string (notice ‘../login.php?username&password’ as url when executing the scriptlogin.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 2083character

as a query string).

Satnam said,

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

PHP interview questions < TechInterviews.com said,

[…] I am trying to assign a variable the value of 0123, but it keeps coming upwith a different number, what’s the problem? - PHP Interpreter treatsnumbers beginning with 0 as octal. Look at the similar PHP interview

questions for more numeric problems. […]

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

20

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 21/59

a set of 5 Qs and then click Continue and then again next 5 and againContinue and so on)I know how to send data to database and the values to different colomns butI dont know how to send data to same row for one person….once it goes tonext 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 iscompleted and start sending data to new row when a new user starts thesurvey.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 regardingthis.

Thanks a lot

Ashik Rahman said,

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

shyambabu said,

6th question answer is $message and $$messageboth are variable declarations.

$message=”ValueA” $$message is equal to $($message)=$ValueA

tarangini said,

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

Vikas Bhambi said,

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

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];

21

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 22/59

Slava said,

How can we register the variables into a session?

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

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

PHP Docs said,

How can I execute a PHP script using command line?

#php -F

Carrie Underwood said,

56. How can we send mail using JavaScript?

document.sendeamil.submit();

Carrie Underwood said,

56. How can we send mail using JavaScript?

document.sendeamil.submit();

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

Jesse said,

Q7)

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

Mohammed Ismail said,

22

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 23/59

Question :

Difference between mysql_connect and mysql_pconnnect

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 formsubmitting, give the case where we can use get and we can use postmethods?Ans :-In the get method the data made available to the action page ( where data isreceived ) 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 willbe 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 andmysql_fetch_array?Ans:-MySQL fetch object will collect first single matching record wheremysql_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, thecontent 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 itdisplays the content of $var on the screen.

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];

23

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 24/59

Use the function split split(“@”,”http://[email protected]”) which returns an arrayany 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 beignored then we have to use the PHP function include_once(). This willprevent 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 isgenerated when we are creating a 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.

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 defaultwill be applied and MyISAM is default

13. How can I execute a PHP script using command line?Ans:-Through php parse you can execute PHP script using command line. Bydefault location of php parser is /var/www/html so set the path of this

24

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 25/59

directory and just use as following#php sample.php

16. What is meant by nl2br()?Ans:-nl2br() inserts html in string

echo 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 usingmysql?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) Startuperrors.

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

Ans:-string strstr ( string str1, string str2) this function search the string str1 forthe first occurrence of the string str2 and returns the part of the string str1from the first occurrence of the string str2. This function is case-sensitive andfor 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 sitehttp://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 beURL encoded and can be use to append with URLs, normaly used to appneddata for GET like someurl.com?var=hello%world

25

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 26/59

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 incontextunset 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 asession?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 ignorescase distinction when matching alphabetic characters.eregi_replace() functionis identical to ereg_replace() except that this ignores case distinction whenmatching 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

26

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 27/59

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

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 availablewhen thatextension has either been compiled into PHP or dynamically loaded atruntime.

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

27

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 28/59

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

a. OCI-Lobb. OCI-Collection

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

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 emailclient 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 notpossible” 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 levelprogramming to PHP. PEAR is a framework and distribution system forreusable PHP components. It eases installation by bringing an automatedwizard, and packing the strength and experience of PHP users into a nicelyorganised OOP library. PEAR also provides a command-line interface that canbe used to automatically install “packages” 

58. What is the purpose of the following files having extensions 1) frm 2) MYD3) 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 thatbegin with the table name and have an extension to indicate the file type.

28

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 29/59

The `.frm’ file stores the table definition.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 getmore 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)

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

Priya said,

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

Nithin said,

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

ex:

stristr function is an Case-insensitive strstrex:

 jeeva arulraj said,

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

Archana said,

Answer to Q. 13.

PHP can be executed from Command Line, using the SAP Interface (SAPI) orServer Application Programming Interface named CLI which means CommandLine Interface.The CLI SAPI was released for the first time with PHP 4.2.0, but was stillexperimental and had to be explicitly enabled with –enable-cli when

29

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 30/59

running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimentaland the option –enable-cli is on by default. You may use –disable-cli todisable it.

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

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>

Nitesh said,

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

Nitesh said,

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

Nitesh said,

Ans of 1: When we submit a form, which has the GET method it pass value inthe 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 theform of Object and we can submit large data from the form.

admin said,

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

30

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 31/59

1. What are the differences between GET and POST methods in formsubmitting, give the case where we can use get and we can use postmethods?

On the server side, the main difference between GET and POST is where thesubmitted 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 methodwill be displayed in the browser’s address field. Data submitted by the POSTmethod will not be displayed anywhere on the browser.

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

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 thefounder 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 formfield. In the JavaScript code, we can call the document.form.submit() functionto 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 andmysql_fetch_array?

MySQL fetch object will collect first single matching record wheremysql_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…’ usingregular _expression of php?

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

31

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 32/59

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

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 onlyand further calling of the file will be ignored then we have to use the PHPfunction 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 isgenerated when we are creating a table in the following

syntax: create table employee(eno int(2),ename varchar(10)) ?

Total 5 types of tables we can create

1. 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 PHPscript file name as the command line argument. For example, "phpmyScript.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 maynot execute properly in command line environment.

32

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 33/59

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

If you change the line: short_open_tag = off in php.ini file. Then your phpZEND 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: echonl2br("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 operatingsystems?

All of those are open source resource. Security of linux is very very more thanwindows. Apache is a better server that IIS both in functionality and security.Mysql is world most popular open source database. Php is more faster thatasp or any other scripting language.

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

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>SETPASSWORD=PASSWORD("Password");We can encode data using base64_encode($string) and can decode usingbase64_decode($string);

22. What are the features and advantages of OBJECT ORIENTEDPROGRAMMING?

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 reducingmaintenance costs. OO programming is also considered to be better atmodeling the real world than is procedural programming. It allows for morecomplicated and flexible interactions. OO systems are also easier for non-

33

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 34/59

technical personnel to understand and easier for them to participate in themaintenance and enhancement of a system because it appeals to naturalhuman cognition patterns.For some systems, an OO approach can speed development time since manyobjects are standard across systems and can be reused. Components thatmanage dates, shipping, shopping carts, etc. can be purchased and easily

modified for a specific system.

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

Traditional programming has the following characteristics:

Functions are written sequentially, so that a change in programming canaffect any code that follows it.If a function is used multiple times in a system (i.e., a piece of code thatmanages 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 fournumerical digits instead of two), all these pieces of code must be found,modified, and tested.Code (sequences of computer instructions) and data (information on whichthe instructions operates on) are kept separate. Multiple sets of code canaccess and modify one set of data. One set of code may rely on data inmultiple 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 problemsthrough 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 anabstraction of a set of real-world things (for example, an object may becreated around "date") The object would contain all information andfunctionality for that thing (A dateobject it may contain labels like January, February, Tuesday, Wednesday. Itmay contain functionality that manages leap years, determines if it is abusiness day or a holiday, etc., See Fig. 1). Ideally, information about aparticular thing should reside in only one place in a system. The informationwithin an object is encapsulated (or hidden) from the rest of the system.A system is composed of multiple objects (i.e., date function, reports, orderprocessing, etc., See Fig 2). When one object needs information from anotherobject, 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 thedate object) These requests are called messages and each object has aninterface 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?

34

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 35/59

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 asglobal 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 functionscan use all attributes of the class whichnames them as a friend, as if they

were themselves members of that class.A friend declaration is essentially a prototype for a member function, butinstead of requiring an implementation with the name of that class attachedby the double colon syntax, a global function or member function of anotherclass 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 asfollows:

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

int f1();};

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

class A{

35

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 36/59

friend class B;};

Friend functions allow binary operators to be defined which combine privatedata in a pair of objects. This is particularly powerful when using the operatoroverloading 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 InterfaceData 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 yes

transient 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 whileexecuting a script - for example, accessing a variable that has not yet beendefined. 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 toinclude() a file which does not exist. By default, these errors are displayed tothe user, but they do not result in script termination.

3. Fatal errors: These are critical errors - for example, instantiating an objectof a non-existent class, or calling a non-existent function. These errors causethe immediate termination of the script, and PHP's default behaviour is todisplay 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 givensubstring 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?

36

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 37/59

You can download asp2php front-end application from the sitehttp://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 equivalentsare translated into these entities.

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

$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. Forexample: urlencode("10.00%") will return "10%2E00%25?. URL encodedstrings 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 imageusing 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 andhow can we change this?

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

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

37

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 38/59

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

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 veryeasy:

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

53. List out the predefined classes in php?

DirectorystdClass __PHP_Incomplete_Class

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

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 methodsare the methods, which are declare in its class but not define. The definitionof 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 methodsmust 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 theform 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 mysqlwill do a repair of only the index tree if the extended is given it will createindex row by row

38

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 39/59

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

A stored procedure is a set of SQL commands that can be compiled andstored 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 providesbetter overall performance because the query has to be parsed only once,

and less information needs to be sent between the server and the client. Youcan also raise the conceptual level by having libraries of functions in theserver. However, stored procedures of course do increase the load on thedatabase server system, as more of the work is done on the server side andless on the client (application) side.Triggers will also be implemented. A trigger is effectively a type of storedprocedure, one that is invoked when a particular event occurs. For example,you can install a stored procedure that is triggered each time a record isdeleted from a transaction table and that stored procedure automaticallydeletes the corresponding customer from a customer table when all histransactions are deleted.Indexes are used to find rows with specific column values quickly. Without anindex, MySQL must begin with the first row and then read through the entiretable 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 quicklydetermine the position to seek to in the middle of the data file without havingto look at all the data. If a table has 1,000 rows, this is at least 100 timesfaster than reading sequentially. If you need to access most of the rows, it isfaster to read sequentially, because this minimizes disk seeks.

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

Database name- 64Table name -64

Fieldname-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 64values

61. What are the other commands to know the structure of table using mysqlcommands 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,

39

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 40/59

63. What is the purpose of the following files having extensions 1) frm 2) MYD3) 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 thatbegin 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 adirectory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers of files in adirectory 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 thenumber 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 MyISAMstorage engine in MySQL 3.23, the maximum table size was increased to65536 terabytes (2567 – 1 bytes). With this larger allowed table size, themaximum effective table size for MySQL databases is usually determined byoperating system constraints on file sizes, not by MySQL internal limits.The InnoDB storage engine maintains InnoDB tables within a tablespace thatcan be created from several files. This allows a table to exceed the maximumindividual file size. The tablespace can include raw disk partitions, whichallows 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 mostup-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 bydatabase.* or a specific table by database.table_nameusername@hotsname can be either username@localhost,

40

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 41/59

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 beachieved until the previous levels have been achieved (there are actually fivenormal forms, but the last two are mainly academic and will not bediscussed).

First Normal Form

The First Normal Form (or 1NF) involves removal of redundant data fromhorizontal rows. We want to ensure that there is no duplication of data in agiven row, and that every column stores the least amount of informationpossible (making the field atomic).

Second Normal Form

Where the First Normal Form deals with redundancy of data across ahorizontal row, Second Normal Form (or 2NF) deals with redundancy of datain vertical columns. As stated earlier, the normal forms are progressive, so toachieve Second Normal Form, your tables must already be in First NormalForm.

Third Normal Form

I have a confession to make; I do not often use Third Normal Form. In ThirdNormal Form we are looking for data in our tables that is not fully dependanton 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];

41

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 42/59

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

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

Disadvantages

An extra download is required to import style information for each documentThe rendering of the document may be delayed until the external style sheetis 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 complexcontexts

No additional downloads necessary to receive style information

Disadvantages

This method can not control styles for multiple documents at once

Inline Styles

42

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 43/59

Advantages

Useful for small quantities of style definitionsCan override other style specification methods at the local level so onlyexceptions 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 multipleelement types within the documentSelector grouping methods can not be used to create complex elementaddressing scenarios

71. What type of inheritance that php supports? Answer: In PHP an extendedclass is always dependent on a single base class, that is, multiple inheritanceis 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 |+—————-+————-+——+—–+———+—————-+| 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 thestarting value for this auto incremented field user_pri_id ,Condition2: Delete the last row(having the field value 2345) and insertanother 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 referencesbetween different tables should usually be done with indexes. You can use theEXPLAIN statement to determine which indexes are used for a SELECT. Seesection 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 runmyisamchk –analyze on a table after it has been loaded with data. Thisupdates 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.) MySQLwill use this to decide which index to choose when you join two tables basedon a non-constant expression. You can check the result from the table

43

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 44/59

analysis by using SHOW INDEX FROM tbl_name and examining the Cardinalityvalue. 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 makequeries 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 alarge table this way, it may take a long time.

In both cases let the value for auto increment field be n then next row willhave 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 crossplatform. 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 tableand create a new temporary table where all rows from each group areconsecutive, and then use this temporary table to discover groups and applyaggregate functions (if any).ORDER BY [col1],[col2],…,[coln]; Tels DBMS according to what columns itshould sort the result. If two rows will hawe the same value in col1 it will tryto sort them according to col2 and so on.GROUP BY [col1],[col2],…,[coln]; Tels DBMS to group results with same valueof 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_namecolumn_definition[FIRST|AFTER col_name]

44

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 45/59

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 tableitself? Use the TRUNCATE TABLE command (deletes only the data inside thetable).

83. When you want to show some part of a text displayed on an HTML page inred font color, what different possibilities are there to do this? What are theadvantages/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 tochange the code of the page. But when we use CSS then it will be easy tochange the CSS file and we can get the desired out put.

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 pagecaching? How can you prevent caching of a certain page (please give severalalternate solutions)?

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

A page that Internet Explorer is browsing is not cached until half of the 64 KBbuffer is filled. Usually, metatags are inserted in the header section of anHTML document, which appears at the beginning of the document. When theHTML 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 thatexact moment. If it is there, it is removed. To properly prevent the Web pagefrom appearing in the cache, place another header section at the end of theHTML ocument. For example:

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

45

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 46/59

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

87. What are the different ways to login to a remote server? Explain themeans, 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 canbe used to identify the URL from within a HTML link tag. Example: The regular _expression should match the tag mysqldump -u user -ppassword –opt -fulldatabase_name > backupfile.sqlThen move the resulting file(s) to your preferred backup areas. If you requiremore information on the mysqldump command, then simply check out thisURL:www.mysql.com/documentation/mysql

Copy all the relevant table files.

If the server isn't updating anything (or you've deliberately killed mysqld forthis purpose) then you can copy all the files with the following extensions inyour MySQL data directory:*.frm*.myd*.myiMake sure you restart the MySQL daemon once you finish copying anddownloading the files to your preferred backup areas.TIP: once you've completed the backup, restart MySQL with the –log-updateswitch. This will allow you to keep track of all modifications done in theMySQL tables since your last 'dump'.To restore your dumps, you should either restore to an existing database orcreate 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 largelydependent 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 informationis incorporated into Web server and browser software, and enables theautomatic 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 ispronounced just like the fruit. The purpose of PEAR is to provide:A structured library of open-sourced code for PHP users

46

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 47/59

A 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/PEARcommunity

PEAR is a community-driven project with the PEAR Group as the governingbody. The project has been founded by Stig S. Bakken in 1999 and quite a lotof 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 intoyour PHP scripts.string COM::COM ( string module_name [, string server_name [, intcodepage]])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 toTRUE in php.ini.codepagespecifies the codepage that is used to convert php-strings to unicode-stringsand 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 emptydocument $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; ?>

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 declaresfirst.then we write session_register().

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

47

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 48/59

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 numericarray, or both.

mysql_fetch_object ( resource result )Returns an object with properties that correspond to the fetched row andmoves the internal data pointer ahead. Returns an object with properties thatcorrespond to the fetched row, or FALSE if there are no more rowsmysql_fetch_row() fetches one row of data from the result associated withthe specified result identifier. The row is returned as an array. Each resultcolumn 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, andwindows?

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 theword 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 beable to enter the commands that you wish to run. My version of Linux usesthe 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 willnot 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 numericalconstants. 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 eachvalue with a comma.command can be any shell command and, as we will see momentarily, can

48

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 49/59

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, ourmycronjob 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 scriptin this manner, nothing will happen (barring very special configurations that

have PHP compiled as an executable, as opposed to an Apache module). Thereason is that, in order for PHP to be parsed, it needs to be passed throughApache. In other words, the page needs to be called via a browser or othermeans of retrieving Web content.For our purposes, I’ll assume that your server configuration includes wget, asis the case with most default configurations. To test your configuration, log into 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 yoursystem.You could execute the PHP by invoking wget on the URL to the page, like so:# wget http://www.example.com/file.php

Now, let’s go back to the mailstock.php file we created in the first part of thisarticle. We saved it in our document root, so it should be accessible via theInternet. Remember that we wanted it to run at 4PM Eastern time, and sendyou your precious closing bell report? Since I’m located in the Easterntimezone, we can go ahead and set up our crontab to use 4:00, but if you liveelsewhere, you might have to compensate for the time difference whensetting 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 accountand your Web site. The online payment gateway allows you to immediatelyverify credit card transactions and authorize funds on a customer’s credit carddirectly from your Web site. It then passes the transaction off to yourmerchant bank for processing, commonly referred to as transaction batching

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

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

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

Three are three types of errors:

1. Notices: These are trivial, non-critical errors that PHP encounters whileexecuting a script - for example, accessing a variable that has not yet beendefined. By default, such errors are not displayed to the user at all - although,as you will see, you can change this default behaviour.

49

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 50/59

2. Warnings: These are more serious errors - for example, attempting toinclude() a file which does not exist. By default, these errors are displayed tothe user, but they do not result in script termination.

3. Fatal errors: These are critical errors - for example, instantiating an objectof 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 todisplay 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 aattached?

$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 validupload file (meaning that it was uploaded via PHP's HTTP POST uploadmechanism). If the file is valid, it will be moved to the filename given bydestination.

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

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

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

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

50

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 51/59

Return-path: Return path is when there is a mail delivery failure occurs thenwhere 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 thatvariable 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, itbecomes 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, andthe result will be a float. Otherwise, the operands will be interpreted asintegers, and the result will also be an integer. Note that this does NOTchange the types of the operands themselves; the only change is in how theoperands 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 thevar_dump() function.Note: The behavior of an automatic conversion to array is currentlyundefined.

Since PHP (for historical reasons) supports indexing into strings via offsetsusing the same syntax as array indexing, the example above leads to aproblem: 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 offsetidentification, so $a becomes "f", the result of this automatic conversionhowever should be considered undefined. PHP 4 introduced the new curlybracket syntax to access characters in string, use this syntax instead of theone presented above:

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

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 integratePHP into a Java Servlet environment, which is the more stable and efficientsolution, or integrate Java support into PHP. The former is provided by a SAPImodule that interfaces with the Servlet server, the latter by this Javaextension.The Java extension provides a simple and effective means for creating and

51

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 52/59

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:ssa 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 optionsNameDefaultChangeable java.class.path

NULLPHP_INI_ALLName Default Changeable java.homeNULLPHP_INI_ALL java.library.pathNULLPHP_INI_ALL java.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 usa

4 phptalk.com germany5 mysql.com usa6 sureshbabu canada7 phpbuddy.com pakistan8. phptalk.com austria9. phpfreaks.com sourthafrica10. phpsupport.net russia11. sureshbabu australia

52

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 53/59

12. sureshbabu nepal13. phptalk.com italy

Write a select query that will displayed the duplicated site name and howmany 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 sideemail 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; }}

Tejas vadalia said,

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

hita said,

Answer for Q.No:7

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

hita said,

Answer of Q.No:48

count(array) or sizeof(array)

Sajeesh Francis said,

Answer for Q.No:7

53

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 54/59

$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.”;}

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 theclass 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 notlose its value when program execution leaves this scope.Final: Final keyword prevents child classes from overriding a method byprefixing the definition with final. If the class itself is being defined final thenit cannot be extended.

Rahul Chahwala said,

Answer to que 7

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

 //outputabc.com

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

Arghadip Acharya said,

Answer of Question Number 1:

54

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 55/59

This is not the only answer between GET & POST method posted byMr.Cahndu.Ther are another differences:Using GET method, only 255 datas can be submitted (For some browser itexceeds 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 isrequired.

Thank You.

nilanjan karmakar said,

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

document.form1.submit();}

nilanjan karmakar (question:8) said,

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

shiva.G said,

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

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.

appsaheb bagali said,

Q no 1)

55

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 56/59

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 throughHeader 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 GETMethod data

will store in server logs of Apache. from they can keep track of theFrequentlly searched data

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

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 a160-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(), orsha1 functions. password() is the function used for MySQL’s own userauthentication system. It returns a 16-byte string for MySQL versions prior to4.1, and a 41-byte string (based on a double SHA-1 hash) for versions 4.1and up. md5() is available from MySQL version 3.23.2 and sha1() was addedlater in 4.0.2.

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

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, ratherthan what they don’t know.The all above question need one to memorized PHP in depth.

Rakesh Chandel said,

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

56

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 57/59

rishi said,

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

step 2: y=x-ystep 3: x=x-y

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 definingfirst functions and calling them on some events like “onClick”,”onBlur” etc.

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 valuesare 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 informationsecurity is required.

-POST method does not display any content in the address bar so,completebookmarking 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-informationsecurity.-POST method is

Niladri said,

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

Niladri said,

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

Niladri said,

What is the utility of GD Library ?

Hitu Patel said,

57

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 58/59

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

eregi_replace — replace regular expression case insensitiveereg_replace — replace regular expression

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

Hitu Patel said,

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

Hitu Patel said,

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

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

For Decriyption use AES_DECRYPT()

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.

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.

Manokaran said,

Difference between Session and Cookie in PHP ?

58

8/8/2019 34984194 25524375 PHP Interview Questions

http://slidepdf.com/reader/full/34984194-25524375-php-interview-questions 59/59

Session variables are stored in Server system.

Cookie variables are stored in Client system.