php interview questions

55
PHP Interview Questions - PHP Interview Questions and Answers 1) What is the difference between strstr & stristr? For strstr, the syntax is: string strstr(string $string,string $str ); The function strstr will search $str in $string. If it finds the string means it will return string from where it finds the $str upto end of $string. For Example: $string = "http://yahoomail.com"; $str="yahoomail"; The output is "yahoomail.com". The main difference between strstr and stristr is of case sensitivity. The former consider the case difference and later ignore the case difference. 2) What is the difference between explode and split? Split function splits string into array by regular expression. Explode splits a string into array by string. For Example:

Upload: muneer-uc

Post on 22-Jan-2016

39 views

Category:

Documents


0 download

DESCRIPTION

Php Interview Question

TRANSCRIPT

Page 1: PHP Interview Questions

PHP Interview Questions - PHP Interview Questions and Answers1) What is the difference between strstr & stristr?

For strstr, the syntax is: string strstr(string $string,string $str ); The function strstr will search $str in $string. Ifit finds the string means it will return string from where it finds the $str upto end of $string.For Example:$string = "http://yahoomail.com";$str="yahoomail";The output is "yahoomail.com". The main difference between strstr and stristr is of case sensitivity. Theformer consider the case difference and later ignore the case difference.

2) What is the difference between explode and split?

Split function splits string into array by regular expression. Explode splits a string into array by string.For Example:explode(" and", "India and Pakistan and Srilanka");split(" :", "India : Pakistan : Srilanka");Both of these functions will return an array that contains India, Pakistan, and Srilanka.

3) How can you avoid execution time out error while fetching record from MySQL?

set_time_limit -- Limits the maximum execution timeFor Example:set_time_limit(0);If you set to 0 you say that there is not limit.

Page 2: PHP Interview Questions

4) Write a SQL query that displays the difference between the highest and lowest salaries of a database table

"employees". Label the column as DIFFERENCE.Select max(sal)-min(sal) as Difference from employees;

5) What is the difference between require() and include()?

Both of these constructs includes and evaluates the specific file. The two functions are identical in every wayexcept how they handle failure. If filepath not found, require() terminates the program and gives fatal error,but include() does not terminate the program; It gives warning message and continues to program.include() produces a Warning while require() results in a Fatal Error if the filepath is not correct.

6) What is the difference between echo and print?

Main difference between echo() and print() is that echo is just an statement not a function and doesn't return'svalue or it just prints a value whereas print() is an function which prints a value and also it returns value.We cannot pass arguments to echo since it is just a statement whereas print is a function and we can passarguments to it and it returns true or false. print can be used as part of a more complex expression whereasecho cannot. echo is marginally faster since it doesn't set a return value.

7) An examiner awards the highest mark 75 and the lowest mark 25, the pass marks being 40. Themoderator wants to change the highest mark to 250 and the lowest marks to 100 using the linear formula

Page 3: PHP Interview Questions

y=ax+b. The revised pass marks will be:A. 145B. 150C. 160D. 400/3Give the correct option.y=ax+b100=25a+b250=75a+bSolve it get and b and then puty=40a+bAnswer: 145

8) A and B are shooters and having their exam. A and B fall short of 10 and 2 shots respectively to thequalifying mark. If each of them fired at least one shot and even by adding their total score together, they fallshort of the qualifying mark, what is the qualifying mark?Answer: 11As A is short by 10 - he has shot 1As B is short by 2 - he has shot 99+1=10 and 10 < 11

9) In objective test a correct answer score 4 marks and on a wrong answer 2 marks. A student scores 480marks from 150 questions. How many answers were correct?A. 120C. 110D. 150Answer: B i.e. 1304x-2y=480x+y=150Then X is 130 so 130 is correct answer.

Page 4: PHP Interview Questions

10) An INK bug starts jumping 1 meter to each direction north, south, east and west respectively. It marks apoint in the new locations. It comes back to its original point after jumping in all directions. It again starts thesame process from the newly drawn unique points. Totally how many points did the bug mark?

11) A guy walks at 4kmph from a point. After 4hrs a cyclist starts from the same point at 10kmph. At whatdistance will they meet from the starting point?Answer: 26.66kmExplanation: We have, s=vt where s=distance. Since both meet at same point, both travels same distance=skm. Now, equating, 10(t+4) = 4t ------> t=20/3sub. t=20/3 in s=4t---------> s = 26.66km

12) What's the difference between COPY OF A FILE & MOVE_UPLOAD_FILE in file uploading?

Move: This function checks to ensure that the file designated by filename is a valid upload file (meaning that itwas uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filenamegiven by destination.If filename is not a valid upload file, then no action will occur, and move_uploaded_file() will return FALSE.Copy: Makes a copy of a file. Returns TRUE if the copy succeeded, FALSE otherwise.

13) How do you insert single & double quotes in MySQL db without using PHP?

&amp; / &quote;Alternately, escape single quote using forward slash \' . In double quote you don't need to escape quotes.

Page 5: PHP Interview Questions

Insert double quotes as "".

14) What do you need to do to improve the performance (speedy execution) for the script you have written?

If your script is to retrieve data from Database, you should use "Limit" syntax. Break down the non dynamicsections of website which need not be repeated over a period of time as include files.

15) How do you capture audio/video in PHP?

You need a module installed - FFMPEG. FFmpeg is a complete solution to record, convert and stream audioand video. It includes libavcodec, the leading audio/video codec library. FFmpeg is developed under Linux,but it can be compiled under most operating systems, including Windows.

16) How do you know (status) whether the recipient of your mail had opened the mail i.e. read the mail?

Embed an URL in a say 0-byte image tag may be the better way to go. In other word, you embed an invisibleimage on you html email and when the src URL is being rendered by the server, you can track whether yourrecipients have view the emails or not.

17) What is random number?

A random number is a number generated by a process, whose outcome is unpredictable, and which cannotbe sub sequentially reliably reproduced.

18) What is difference between srand & shuffle?

Page 6: PHP Interview Questions

The srand function seeds the random number generator with seed and shuffle is used for shuffling the arrayvalues.shuffle - This function shuffles (randomizes the order of the elements in) an array. This function assigns newkeys for the elements in array. It will remove any existing keys you may have assigned, rather than justreordering the keys.srand - Seed the random number generator

19) How can we remove duplicate values from an array?

array_unique() funciton can be used for the purpose.

20) How do I find out weather a number is odd or even?

if (number%2==0 ) then even else odd.

21) How can we get the ID generated from the previous insert operation?

SELECT MAX(ID) from tablename;

22) How to limit the number of rows to 5 that I get out of my database?

Select * from tablename LIMIT 0, 5;

23) How to store binary data in MySQL?

Use BLOB data type for the database field.

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

Page 7: PHP Interview Questions

We can submit a form using the JavaScript. Example: document.formname.submit();

25) How can I maintain the count of how many persons have hit my site?

26) What is difference between mysql_fetch_array(), mysql_fetch_row() and mysql_fetch_object()?

mysql_fetch_array - Fetch the all matching records of results.mysql_fetch_object - Fetch the first single matching record of results.mysql_fetch_row - fetches a result row as array.

27) How to make a download page in own site, where I can know that how many file has been loaded byparticular user or particular IP address?

We can log the IP addresses in one database table while downloading the file. This way we can count andcheck the no. of rows inserted for a particular download.

28) What is difference between mysql_connect and mysql_pconnect?

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

29) What is the difference between “Insert”, “Update” and “Modify” events?

Page 8: PHP Interview Questions

INSERT - Add a new record into the database table.MODIFY - If record is available it modifies otherwise it wont modify.UPDATE - If record is available it updates the record otherwise it creates a new record.

30) How I can get IP address?

getenv("REMOTE_ADDR");

31) How to make a login page where once the user has logged in will go back to the page it came from tologin page?

32) How do we know properties of the browser?You can gather a lot of information about a person's computer by using $_SERVER['HTTP_USER_AGENT'].This can tell us more about the user's operating system, as well as their browser. For example I am revealedto be Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.3when visiting a PHP page.This can be useful to programmers if they are using special features that may not work for everyone, or ifthey want to get an idea of their target audience. This also is important when using the get_browser() functionfor finding out more information about the browser's capabilities. By having this information the user can bedirected to a version of your site best suited to their browser.get_browser() attempts to determine the capabilities of the user's browser. This is done by looking up thebrowser's information in the browscap.ini file.echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";$browser = get_browser();foreach ($browser as $name => $value)

Page 9: PHP Interview Questions

{echo "<b>$name</b> $value <br />\n";}33) What is difference between require_once(), require(), include(). Because all these function are used tocall a file in another file.Difference between require() and require_once(): require() includes and evaluates a specific file, whilerequire_once() does that only if it has not been included before (on the same page).So, require_once() is recommended to use when you want to include a file where you have a lot of functionsfor example. This way you make sure you don't include the file more times and you will not get the "functionre-declared" error.Difference between require() and include() is that require() produces a FATAL ERROR if the file you want toinclude is not found, while include() only produces a WARNING.There is also include_once() which is the same as include(), but the difference between them is the same asthe difference between require() and require_once().34) If you have to work with dates in the following format: "Tuesday, February 14, 2006 @ 10:39 am", howcan you convert them to another format that is easier to use?The strtotime function can convert a string to a timestamp.A timestamp can be converted to date format. So it is best to store the dates as timestamp in the database,and just output them in the format you like.So let's say we have $date = "Tuesday, February 14, 2006 @ 10:39 am";In order to convert that to a timestamp, we need to get rid of the "@" sign, and we can use the remainingstring as a parameter for the strtotime function.So we have$date = str_replace("@ ","",$date);

Page 10: PHP Interview Questions

$date = strtotime($date);Now $date is a timestamp and we can say:echo date("d M Y",$date);

35) What is CAPTCHA?

CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart. Toprevent spammers from using bots to automatically fill out forms, CAPTCHA programmers will generate animage containing distorted images of a string of numbers and letters. Computers cannot determine what thenumbers and letters are from the image but humans have great pattern recognition abilities and will be ableto fairly accurately determine the string of numbers and letters. By entering the numbers and letters from theimage in the validation field, the application can be fairly assured that there is a human client using it.36) What is the difference between sessions and cookies?37) What is the difference between $x and $$x ?$x is simple variable. $$x is reference variable or infact a variable of variable. A variable variable allows us tochange the name of a variable dynamically.<?$x = "this";$$x = "is cake";?>The $$ is the syntax used in PHP for a variable variable. I can now call the two variables $x and $$x twoways.<?echo "$x ${$x}";?><?echo "$x $this";

Page 11: PHP Interview Questions

?>Both of these will return the string "this is cake". Notice that $$x is written as ${$x} in echo. This lets PHPknow that you are using the variable $$x and not $ and $x

38) What is meant by nl2br()?New line (\n) to Break tag (<BR>) conversion.

39) What are the current versions of apache, PHP, and MySQL?

40) What are the reasons for selecting lamp (Linux, Apache, MySQL, PHP) instead of combination of othersoftware programs, servers and operating systems?

41) How can we encrypt and decrypt a data present in a MySQL table using MySQL?AES_ENCRYPT(str,key_str) , AES_DECRYPT(crypt_str,key_str)

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

43) What does PHP stands for and who is the father of PHP? Explain the changes in PHP versions?

44) How can we create a database using PHP and MySQL?

45) What is meant by urlencode() and urldecode()?string urlencode(str)

When str contains a string like this “hello world” and the return value will be URL encoded and can be use toappend with URLs, normally used to append data for GET like someurl.com?var=hello%worldstring urldocode(str)

Page 12: PHP Interview Questions

This will simple decode the GET variable’s value. Example: echo (urldecode($_GET_VARS[var])) will output“hello world”46) 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 context. unset will set UNSET thespecified variable.unlink is used to delete a file. unset is used to destroy an earlier declared variable.

47) What are the different types of errors in PHP?

1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example,accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all- although you can change this default behavior.2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist.By default, these errors are displayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or callinga non-existent function. These errors cause the immediate termination of the script, and PHP’s defaultbehavior is to display them to the user when they take place.

48) How can we create a session variable & terminate it?$_SESSION[’name’] = “Chinmay”;To destroy a session: unset($_SESSION[’name’]);

49) How to Create a Cookie & destroy it in PHP?setcookie(”variable”,”value”,”time”);variable - name of the cookie variable

Page 13: PHP Interview Questions

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.Destroy a cookie by specifying expiry timeExample: setcookie(”test”,$i,time()-3600); // already expired timeReset a cookie by specifying its name onlysetcookie(”test”);

50) What is the difference between sizeof($array) and count($array)?sizeof($array) - This function is an alias of count()count($array) - If you just pass a simple variable instead of an array it will return 1.

Questions : 1

Who is the father of PHP ?

Answers : 1

Rasmus Lerdorf is known as the father of PHP.

Questions : 2

What is the difference between $name and $$name?

Answers : 2

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

Page 14: PHP Interview Questions

Questions : 3

How can we submit a form without a submit button?

Answer : 3

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

Questions : 4

In how many ways we can retrieve the data in the result set ofMySQL using PHP?

Answer : 4

We can do it by 4 Ways1. mysql_fetch_row. , 2. mysql_fetch_array , 3. mysql_fetch_object4. mysql_fetch_assoc

Questions : 5

What is the difference between mysql_fetch_object andmysql_fetch_array?

Answers : 5

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

Questions : 6

What are the differences between Get and post methods.

Answ There are some defference between GET

Page 15: PHP Interview Questions

ers : 6

and POST method 1. GET Method have some limit like only 2Kb data able to send for request But in POST method unlimited data can we send 2. when we use GET method requested data show in url but Not in POST method so POST method is good for send sensetive request

Questions : 7

How can we extract string "pcds.co.in " from a string "http://[email protected] regular expression of PHP?

Answers : 7

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

Questions : 8

How can we create a database using PHP and MySQL?

Answers : 8

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

Questions : 9

What are the differences between require and include?

Answers : 9

Both include and require used to include a file but when included file not found Include send Warning where as Require send Fatal Error .

Questions : 10

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

Page 16: PHP Interview Questions

Answers : 10

  Yes we can use include("xyz.php") more than one time in any page. but it create a prob when xyz.php file contain some funtions declaration then error will come for already declared function in this file else not a prob like if you want to show same content two time in page then must incude it two time not a prob

Questions : 11

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

Answers : 11

 Following tables (Storage Engine) we can create1. MyISAM(The default storage engine IN MYSQL Each MyISAM table is stored on disk in three files. The files have names that begin with the table name and have an extension to indicate the file type. An .frm file stores the table format. The data file has an .MYD (MYData) extension. The index file has an .MYI (MYIndex) extension. )2. InnoDB(InnoDB is a transaction-safe (ACID compliant) storage engine for MySQL that has commit, rollback, and crash-recovery capabilities to protect user data.)3. Merge4. Heap (MEMORY)(The MEMORY storage engine creates tables with contents that are stored in memory. Formerly, these were known as HEAP tables. MEMORY is the preferred term, although HEAP remains supported for

Page 17: PHP Interview Questions

backward compatibility. )5. BDB (BerkeleyDB)(Sleepycat Software has provided MySQL with the Berkeley DB transactional storage engine. This storage engine typically is called BDB for short. BDB tables may have a greater chance of surviving crashes and are also capable of COMMIT and ROLLBACK operations on transactions) 6. EXAMPLE 7. FEDERATED (It is a storage engine that accesses data in tables of remote databases rather than in local tables. )8. ARCHIVE (The ARCHIVE storage engine is used for storing large amounts of data without indexes in a very small footprint. )9. CSV (The CSV storage engine stores data in text files using comma-separated values format.)10. BLACKHOLE (The BLACKHOLE storage engine acts as a "black hole" that accepts data but throws it away and does not store it. Retrievals always return an empty result)

Questions : 12

 What is use of header() function in php ?

Answers : 12

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

Page 18: PHP Interview Questions

seen..Questions : 13

How can I execute a PHP script using command line?

Answers : 13

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

Questions : 14

Suppose your Zend engine supports the mode <? ?> Then how can uconfigure your PHP Zend engine to support <?PHP ?> mode ?

Answers : 14

In php.ini file:setshort_open_tag=onto make PHP support

Questions : 15

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

Answers : 15

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

Questions : 16

What is meant by nl2br()?

Answers : 16

Inserts HTML line breaks (<BR />) before all newlines in a string.

Questions : 17

What is htaccess? Why do we use this and Where?

Page 19: PHP Interview Questions

Answers : 17

.htaccess files are configuration files of Apache Server which providea way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particulardocument directory, and the directives apply to that directory, and all subdirectories thereof.

Questions : 18

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

Answers : 18

By using $_SERVER['REMOTE_ADDR'],$_SERVER['HTTP_REFERER'] etc.

Questions : 19

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

Answers : 19

All of those are open source resource. Security of Linux is veryvery more than windows. Apache is a better server that IIS both infunctionality and security. MySQL is world most popular open sourcedatabase. PHP is more faster that asp or any other scripting language.

Questions : 20

How can we encrypt and decrypt a data present in a MySQL tableusing MySQL?

Answ AES_ENCRYPT () and AES_DECRYPT ()

Page 20: PHP Interview Questions

ers : 20Questions : 21

How can we encrypt the username and password using PHP?

Answers : 21

The functions in this section perform encryption and decryption, andcompression and uncompression:encryption decryptionAES_ENCRYT() AES_DECRYPT()ENCODE() DECODE()DES_ENCRYPT() DES_DECRYPT()ENCRYPT() Not availableMD5() Not availableOLD_PASSWORD() Not availablePASSWORD() Not availableSHA() or SHA1() Not availableNot available UNCOMPRESSED_LENGTH()

Questions : 22

What are the features and advantages of object-orientedprogramming?

Answers : 22

One of the main advantages of OO programming is its ease ofmodification; objects can easily be modified and added to a system thereby reducing maintenance costs. OO programming is also considered to bebetter at modeling the real world than is procedural programming. Itallows for more complicated and flexible interactions. OO systems are

Page 21: PHP Interview Questions

also easier for non-technical personnel to understand and easier forthem to participate in the maintenance and enhancement of a systembecause it appeals to natural human cognition patterns.For some systems, an OO approach can speed development time since manyobjects are standard across systems and can be reused. Components thatmanage dates, shipping, shopping carts, etc. can be purchased and easilymodified for a specific system

Questions : 23

What are the differences between procedure-oriented languages andobject-oriented languages?

Answers : 23

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

Ques What is the use of friend function?

Page 22: PHP Interview Questions

tions : 24Answers : 24

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

Questions : 25

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

Answer : 25

Public: Public declared items can be accessed everywhere.Protected: Protected limits access to inherited and parentclasses (and to the class that defines the item).

Page 23: PHP Interview Questions

Private: Private limits visibility only to the class that definesthe item.Static: A static variable exists only in a local function scope,but it does not lose its value when program execution leaves this scope.Final: Final keyword prevents child classes from overriding amethod by prefixing the definition with final. If the class itself isbeing defined final then it cannot be extended.transient: A transient variable is a variable that may notbe serialized. volatile: a variable that might be concurrently modified by multiplethreads should be declared volatile. Variables declared to be volatilewill not be optimized by the compiler because their value can change atany time.

Questions : 26

What are the different types of errors in PHP?

Answer : 26

Three are three types of errors:1. Notices: These are trivial,non-critical errors that PHP encounters while executing a script – forexample, accessing a variable that has not yet been defined. By default,such errors are not displayed to the user at all – although, as you will

Page 24: PHP Interview Questions

see, you can change this default behavior.2. Warnings: These are more serious errors – for example, attemptingto include() a file which does not exist. By default, these errors aredisplayed to the user, but they do not result in script termination.3. Fatal errors: These are critical errors – for example,instantiating an object of a non-existent class, or calling anon-existent function. These errors cause the immediate termination ofthe script, and PHP's default behavior is to display them to the userwhen they take place.

Questions : 27

What is the functionality of the function strstr and stristr?

Answers : 27

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

Questions : 28

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

Answ There are lot of difference among these

Page 25: PHP Interview Questions

er : 28

three version of php1>Php3 is oldest version after that php4 came and current version is php5 (php5.3) where php6 have to come 2>Difference mean oldest version have less functionality as compare to new one like php5 have all OOPs concept now where as php3 was pure procedural language constructive like C In PHP5 1. Implementation of exceptions and exception handling2. Type hinting which allows you to force the type of a specific argument3. Overloading of methods through the __call function4. Full constructors and destructors etc through a __constuctor and __destructor function5. __autoload function for dynamically including certain include files depending on the class you are trying to create.6 Finality : can now use the final keyword to indicate that a method cannot be overridden by a child. You can also declare an entire class as final which prevents it from having any children at all.7 Interfaces & Abstract Classes8 Passed by Reference : 9 An __clone method if you really want to duplicate an object

Questions : 29

How can we convert asp pages to PHP pages?

Page 26: PHP Interview Questions

Answer : 29

there are lots of tools available for asp to PHP conversion. you cansearch Google for that. the best one is available athttp://asp2php.naken.cc./

Questions : 30

What is the functionality of the function htmlentities?

Answer : 30

Convert all applicable characters to HTML entitiesThis function is identical to htmlspecialchars() in all ways, exceptwith htmlentities(), all characters which have HTML character entityequivalents are translated into these entities.

Questions : 31

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

Answer : 31

$second = date("s");

Questions : 32

How can we convert the time zones using PHP?

Answer : 32

By using date_default_timezone_get and date_default_timezone_set function on PHP 5.1.0<?php// Discover what 8am in Tokyo relates to on the East Coast of the US

Page 27: PHP Interview Questions

// Set the default timezone to Tokyo time:date_default_timezone_set('Asia/Tokyo');

// Now generate the timestamp for that particular timezone, on Jan 1st, 2000$stamp = mktime(8, 0, 0, 1, 1, 2000);

// Now set the timezone back to US/Easterndate_default_timezone_set('US/Eastern');

// Output the date in a standard format (RFC1123), this will print:// Fri, 31 Dec 1999 18:00:00 ESTecho '<p>', date(DATE_RFC1123, $stamp) ,'</p>';?>

Questions : 33

What is meant by urlencode and urldocode?

Answer : 33

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

Page 28: PHP Interview Questions

media type.

urldecode decodes any %##encoding in the given string.

Questions : 34

What is the difference between the functions unlink and unset?

Answer : 34

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

Questions : 35

How can we register the variables into a session?

Answer : 35

$_SESSION['name'] = "sonia";

Questions : 36

How can we get the properties (size, type, width, height) of animage using PHP image functions?

Answer : 36

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 t

Questions : 37

How can we get the browser properties using PHP?

Answer :

By using $_SERVER['HTTP_USER_AGENT']

Page 29: PHP Interview Questions

37 variable.

Questions : 38

What is the maximum size of a file that can be uploaded using PHPand how can we change this?

Answer : 38

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

Questions : 39

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

Answer : 39

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

Questions : 40

How can we take a backup of a MySQL table and how can we restoreit. ?

Answer : 40

To backup: BACKUP TABLE tbl_name[,tbl_name…] TO'/path/to/backup/directory'RESTORE TABLE tbl_name[,tbl_name…] FROM '/path/to/backup/directory'mysqldump: Dumping Table Structure and DataUtility to dump a database or a collection of database for backup orfor transferring the data to another SQL server (not necessarily a MySQLserver). The dump will contain SQL statements to create the table and/orpopulate the table.

Page 30: PHP Interview Questions

-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 ifyou just want to get a dump of the structure for a table!

Questions : 41

How can we optimize or increase the speed of a MySQL selectquery?

Answer : 41

first of all instead of using select * from table1, use selectcolumn1, column2, column3.. from table1

Look for the opportunity to introduce index in the table you arequerying.

use limit keyword if you are looking for any specific number ofrows from the result set.

Questions : 42

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

Answer : 42

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

Questions : 43

How can we destroy the session, how can we unset the variable ofa session?

Answer :

session_unregister — Unregister a global variable from the current

Page 31: PHP Interview Questions

43 sessionsession_unset — Free all session variables

Questions : 44

How can we set and destroy the cookie n php?

Answer : 44

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

Questions : 45

How many ways we can pass the variable through the navigationbetween the pages?

Answer : 45

GET/QueryString POST

Questions : 46

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

Answer : 46

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

Page 32: PHP Interview Questions

Questions : 47

What are the different functions in sorting an array?

Answer : 47

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

Questions : 48

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

Answer : 48

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

Questions : 49

what is session_set_save_handler in PHP?

Answer : 49

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

Questions : 50

How can I know that a variable is a number or not using aJavaScript?

Answer :

bool is_numeric ( mixed var)Returns TRUE if var is a number or a

Page 33: PHP Interview Questions

50 numeric string, FALSE otherwise.or use isNaN(mixed var)The isNaN() function is used to check if a value is not a number.

Questions : 51

List out some tools through which we can draw E-R diagrams formysql.

Answer : 51

Case StudioSmart Draw

Questions : 52

How can I retrieve values from one database server and store themin other database server using PHP?

Answer : 52

we can always fetch from one database and rewrite to another. hereis a nice solution of it.$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);$db2 = mysql_connect("host","user","pwd")mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);At this point you can only fetch records from you previous ResultSet,i.e $res1 – But you cannot execute new query in $db1, even if yousupply the link as because the link was overwritten by the new db.so at this point the following script will fail$res3 = mysql_query("query",$db1); //this will failSo how to solve that?

take a look below.

Page 34: PHP Interview Questions

$db1 = mysql_connect("host","user","pwd")mysql_select_db("db1", $db1);$res1 = mysql_query("query",$db1);

$db2 = mysql_connect("host","user","pwd", true)mysql_select_db("db2", $db2);$res2 = mysql_query("query",$db2);

So mysql_connect has another optional boolean parameter whichindicates whether a link will be created or not. as we connect to the$db2 with this optional parameter set to 'true', so both link willremain live.

now the following query will execute successfully.$res3 = mysql_query("query",$db1);

Questions : 53

List out the predefined classes in PHP?

Answer : 53

DirectorystdClass__PHP_Incomplete_Classexceptionphp_user_filter

Questions : 54

How can I make a script that can be bi-language (supportsEnglish, German)?

Page 35: PHP Interview Questions

Answer : 54

You can maintain two separate language file for each of thelanguage. all the labels are putted in both language files as variablesand assign those variables in the PHP source. on runtime choose therequired language option.

Questions : 55

What are the difference between abstract class and interface?

Answer : 55

Abstract class: abstract classes are the class where one or moremethods are abstract but not necessarily all method has to be abstract.Abstract methods are the methods, which are declare in its class but notdefine. The definition of those methods must be in its extending class.Interface: Interfaces are one type of class where all the methods areabstract. That means all the methods only declared but not defined. Allthe methods must be define by its implemented class.

Questions : 56

How can we send mail using JavaScript?

Answer : 56

JavaScript does not have any networking capabilities as it isdesigned to work on client site. As a result we can not send mails usingJavaScript. But we can call the client side mail protocol mailto

Page 36: PHP Interview Questions

via JavaScript to prompt for an email to send. this requires the clientto approve it.

Questions : 57

How can we repair a MySQL table?

Answer : 57

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

Questions : 58

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

Answer : 58

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 tokeep re-issuing the entire query but can refer to the stored procedure.This provides better overall performance because the query has to beparsed only once, and less information needs to be sent between theserver and the client. You can also raise the conceptual level by havinglibraries of functions in the server. However, stored procedures ofcourse do increase the load on the database server system, as more of

Page 37: PHP Interview Questions

the work is done on the server side and less on the client (application)side.Triggers will also be implemented. A trigger is effectively a type ofstored procedure, one that is invoked when a particular event occurs.For example, you can install a stored procedure that is triggered eachtime a record is deleted from a transaction table and that storedprocedure automatically deletes the corresponding customer from acustomer table when all his transactions are deleted.Indexes are used to find rows with specific column values quickly.Without an index, MySQL must begin with the first row and then readthrough the entire table to find the relevant rows. The larger thetable, the more this costs. If the table has an index for the columns inquestion, MySQL can quickly determine the position to seek to in themiddle of the data file without having to look at all the data. If atable has 1,000 rows, this is at least 100 times faster than readingsequentially. If you need to access most of the rows, it is faster toread sequentially, because this minimizes disk seeks.

Questions : 59

What is the maximum length of a table name, database name, andfieldname in MySQL?

Page 38: PHP Interview Questions

Answer : 59

The following table describes the maximum length for each type ofidentifier.

IdentifierMaximum Length(bytes)

Database 64Table 64Column 64Index 64Alias 255There are some restrictions on the characters that may appear inidentifiers:

Questions : 60

How many values can the SET function of MySQL take?

Answer : 60

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

Questions : 61

What are the other commands to know the structure of table usingMySQL commands except explain command?

Answer : 61

describe Table-Name;

Questions : 62

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

Answer : 62

The '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.

Page 39: PHP Interview Questions

The index file has a '.MYI' (MYIndex) extension,

Questions : 63

What is the purpose of the following files having extensions 1) .frm2) .myd 3) .myi? What do these files contain?

Answer : 63

In MySql, the default table type is MyISAM.Each MyISAM table is stored on disk in three files. The files have namesthat begin with the table name and have an extension to indicate thefile type.The '.frm' file stores the table definition.The data file has a '.MYD' (MYData) extension.The index file has a '.MYI' (MYIndex) extension,

Questions : 64

What is maximum size of a database in MySQL?

Answer : 64

If the operating system or filesystem places a limit on the numberof files in a directory, MySQL is bound by that constraint.The efficiency of the operating system in handling large numbers offiles in a directory can place a practical limit on the number of tablesin a database. If the time required to open a file in the directoryincreases significantly as the number of files increases, database

Page 40: PHP Interview Questions

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