PHP FAQ

PHP Interview Questions -9

1. What is an Array in PHP?

An array in PHP is really an ordered map of pairs of keys and values.

2.What is the basic syntax of Php??

<?php
?>
A PHP scripting block can be placed anywhere in the document.

3. What is the name of the scripting engine that powers PHP?

PHP is a scripting engine called the Zend Engine 2.

4. What is the difference between PHP4 and PHP5?

PHP4 cannot support oops concepts and Zend engine 1 is used.
PHP5 supports oops concepts and Zend engine 2 is used. Error supporting is increased in PHP5. XML and SQLLite will is increased in PHP5

5.What is the difference between static and Dynamic Web Sites?

The Web sites were made up of a collection of documents written in the HTML language. The pages were text based, simple, and static. Every time the user reloaded a page in his or her browser, it looked exactly the same. It consisted of HTML text, images, and links.A dynamic Web site is one with content that is regenerated every time a user visits or reloads the site. Although it can be as simple as displaying the current date and time, in most cases it requires the use of a database, which contains the site?s information, and a scripting language that can retrieve the information from the database. Google and Yahoo! are examples of dynamic sites, search engines that create customized pages based on a key word or phrase you type.

6.What are the advantages of MySQL and PHP?

PHP, a simple and powerful scripting language, and MySQL, a solid and reliable database server, make a perfect marriage between two modern technologies for building databasedriven, dynamic Web sites. Some of the advantages of both PHP and MySQL are :
High performance
Built in libraries
Extensibility
Relatively low cost
Portability
Developer community
Ease of learning

7.What is PHP’s configuration file called?

PHP’s configuration file is called php.ini.

8.Which function would you use to merge two arrays?

You can merge arrays with the array_merge() function.

9.What is a session?

A session is a logical object created by the PHP engine to allow you to preserve data across subsequent HTTP requests.

10.Name a new feature introduced with PHP 5?

PHP 5 introduces (among other things) SQLite support, improved XML support, and a significantly improved object model.

11.What is a persistent cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased.

12.What is the difference between temporary cookies and persistent cookies?

Temporary cookies can not be used for tracking long term information.Persistent cookies can be used for tracking long term information.Temporary cookies are safer because no programs other than the browser can access them.Persistent cookies are less secure because users can open cookie files see the cookie values.

13.What is Session Id?

A session ID is an identification string of a session. Since there might be multiple visitors coming to your Web site at the same time, the PHP engine needs to maintain multiple sessions concurrently. Session IDs are created and maintained by the PHP engine to identify sessions.

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

15.How to Create a Cookie & destroy it in PHP?

setcookie(”variable”,”value”,”time”);
variable - name of the cookie variable
variable - value of the cookie variable
time - expiry time
Example: 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 time
Example: setcookie(”test”,$i,time()-3600); // already expired time
Reset a cookie by specifying its name only
setcookie(”test”);

16.How can we create a session variable & terminate it?

$_SESSION[’name’] = “Chinmay”;
To destroy a session: unset($_SESSION[’name’]);

17.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 calling a non-existent function. These errors cause the immediate termination of the script, and PHP’s default behavior is to display them to the user when they take place.

18.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 the
specified variable.
unlink is used to delete a file. unset is used to destroy an earlier declared variable.

19.What is meant by nl2br()?

New line (\n) to Break tag (<BR>) conversion.

20. What are the reasons for selecting lamp (Linux, Apache, MySQL, PHP) instead of combination of other
software programs, servers and operating systems?

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

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

23. 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 to append with URLs, normally used to append data for GET like someurl.com?var=hello%world
string urldocode(str)
This will simple decode the GET variable’s value. Example: echo (urldecode($_GET_VARS[var])) will output
“hello world”

24. 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 to
change 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 two
ways.
<?
echo "$x ${$x}";
?>
<?
echo "$x $this";
?>
Both of these will return the string "this is cake". Notice that $$x is written as ${$x} in echo. This lets PHP
know that you are using the variable $$x and not $ and $x

25.What is difference between require_once(), require(), include(). Because all these function are used to call a file in another file.

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

26. If you have to work with dates in the following format: "Tuesday, February 14, 2006 @ 10:39 am", how can 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 remaining string as a parameter for the strtotime function.So we have
$date = str_replace("@ ","",$date);
$date = strtotime($date);
Now $date is a timestamp and we can say:
echo date("d M Y",$date);

27. What is CAPTCHA?

CAPTCHA stands for Completely Automated Public Turing Test to tell Computers and Humans Apart. To prevent spammers from using bots to automatically fill out forms, CAPTCHA programmers will generate an image containing distorted images of a string of numbers and letters. Computers cannot determine what the numbers and letters are from the image but humans have great pattern recognition abilities and will be able to fairly accurately determine the string of numbers and letters. By entering the numbers and letters from the image in the validation field, the application can be fairly assured that there is a human client using it.

28. what is the difference between “Insert”, “Update” and “Modify” events?

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.

29.What is difference between mysql_connect and mysql_pconnect?

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

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

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

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

32.How can we submit a form without a submit button?

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

33.How to store binary data in MySQL?

Use BLOB data type for the database field.

34.How to limit the number of rows to 5 that I get out of my database?

Select * from tablename LIMIT 0, 5;

35.How can we get the ID generated from the previous insert operation?

SELECT MAX(ID) from tablename;

36.How do I find out weather a number is odd or even?

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

37.How can we remove duplicate values from an array?

array_unique() funciton can be used for the purpose

38.What is difference between srand & shuffle?

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

39.What is random number?

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

40.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 invisible image on you html email and when the src URL is being rendered by the server, you can track whether your recipients have view the emails or not.

41.In objective test a correct answer score 4 marks and on a wrong answer 2 marks. A student scores 480
marks from 150 questions. How many answers were correct?

B. 130

42.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.Insert double quotes as "".

43. 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 dynamic
sections of website which need not be repeated over a period of time as include files.

44.How do you capture audio/video in PHP?

You need a module installed - FFMPEG. FFmpeg is a complete solution to record, convert and stream audio and 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

45.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 invisible image on you html email and when the src URL is being rendered by the server, you can track whether your recipients have view the emails or not.

46.What is random number?

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

47.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's value 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 pass arguments to it and it returns true or false. print can be used as part of a more complex expression whereas echo cannot. echo is marginally faster since it doesn't set a return value.

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

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

50.How can you avoid execution time out error while fetching record from MySQL?

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

51.If md5() generates the most secure hash, why would you ever use the less secure crc32() and sha1()?

Crypto usage in PHP is simple, but that doesn"t mean it"s free. First off, depending on the data that you"re encrypting, you might have reasons to store a 32-bit value in the database instead of the 160-bit value to save on space. Second, the more secure the crypto is, the longer is the computation time to deliver the hash value. A high volume site might be significantly slowed down, if frequent md5() generation is required.

52.What"s the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars only takes care of <, >, single quote ", double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

53.What"s the difference between md5(), crc32() and sha1() crypto on PHP?

The major difference is the length of the hash generated. CRC32 is, evidently, 32 bits, while sha1() returns a 128 bit value, and md5() returns a 160 bit value. This is important when avoiding collisions.

54.What"s the output of the ucwords() function in the example below? $formatted = ucwords("THIS COLLECTION OF PHP INTERVIEW QUESTIONS");

Output will be THIS IS COLLECTION OF PHP INTERVIEW QUESTIONS. ucwords() makes every first letter of every word capital, but it does not lower-case anything else. To avoid this, and get a properly formatted string, it"s worth using strtolower() first.

55.Would you initialize your strings with single quotes or double quotes in PHP?

Since the data inside the single-quoted string is not parsed for variable substitution, it"s always a better idea speed-wise to initialize a string with single quotes, unless you specifically need variable substitution.

56.I am writing an application in PHP that outputs a printable version of driving directions. It contains some long sentences, and I am a neat freak, and would like to make sure that no line exceeds 50 characters. How do I accomplish that with PHP?

On large strings that need to be formatted according to some length specifications, use wordwrap() or chunk_split().

57.What"s the special meaning of __sleep and __wakeup?

sleep returns the array of all the variables than need to be saved, while __wakeup retrieves them.

58.Are objects passed by value or by reference?

Everything is passed by value. In PHP4 it's true, BUT in PHP5 absolutely not - all objects are passed
by reference.

59.How do you call a constructor for a parent class?

parent::constructor($value)

60.What"s the difference between accessing a class method via -> and via ::?

In PHP, :: is allowed to access methods that can perform static operations, i.e. those, which do not
require object initialization.

61.Are objects passed by value or by reference?

Everything is passed by value. In PHP4 it's true, BUT in PHP5 absolutely not - all objects are passed
by reference.

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

63.How do I find out the number of parameters passed into function in PHP?

func_num_args() function returns the number of parameters/arguments passed to a function in PHP.

64.When are you supposed to use endif to end the conditional statement?

When the original if was followed by : and then the code block without braces

65.Explain the ternary conditional operator in PHP?

Expression preceding the ? is evaluated, if it"s true, then the expression preceding the : is executed, otherwise, the expression following : is executed.

66.Will comparison of string "10" and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared

67.When are you supposed to use endif to end the conditional statement?

When the original if was followed by : and then the code block without braces

68.How do you define a constant?

Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);

69.Will comparison of string "10" and integer 11 work in PHP?

Yes, internally PHP will cast everything to the integer type, so numbers 10 and 11 will be compared.

70.What"s the difference between include and require?

It"s how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.

71.Would you use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?

In this example it wouldn"t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces.

72.How do you define a constant?

Constants in PHP are defined using define() directive, like define("MYCONSTANT", 100);

73.How do you pass a variable by value in PHP?

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

74.When you assign a variable the value of 0123, it keeps coming up with a different number, why?

PHP Interpreter treats numbers beginning with 0 as octal. antalya web tasarĂ„±m / web tasarĂ„±m

75.What Is a Session?

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

76.What is meant by PEAR in php?

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

77.How can we know the number of days between two given dates using PHP?
Simple arithmetic:

$date1 = date('Y-m-d');
$date2 = '2006-07-01';
$days = (strtotime() - strtotime()) / (60 * 60 * 24);
echo "Number of days since '2006-07-01': $days";


78.How can we repair a MySQL table?

The syntex for repairing a mysql table is:

REPAIR TABLE tablename
REPAIR TABLE tablename QUICK
REPAIR TABLE tablename EXTENDED

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

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

$message is a simple variable whereas $$message is a reference variable. Example:
$user = 'bob'

is equivalent to

$holder = 'user';
$$holder = 'bob';

79.What Is a Persistent Cookie?

A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:
*Temporary cookies can not be used for tracking long-term information.
*Persistent cookies can be used for tracking long-term information.
*Temporary cookies are safer because no programs other than the browser can access them.
*Persistent cookies are less secure because users can open cookie files see the cookie values.

80.What does a special set of tags <?= and ?> do in PHP?

The output is displayed directly to the browser. 

81.How do you define a constant?

Via define() directive, like define ("MYCONSTANT", 100);

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

require_once() and include_once() are both the functions to include and evaluate the specified file only once. If the specified file is included previous to the present call occurrence, it will not be done again.

83.What is meant by urlencode and urldecode?

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

84.What is the difference between mysql_fetch_object and mysql_fetch_array?

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

85.How can I execute a PHP script using command line?

Just run the PHP CLI (Command Line Interface) program and provide the PHP script file name as the command line argument. For example, "php myScript.php", assuming "php" is the command to invoke the CLI program.Be aware that if your PHP script was written for the Web CGI interface, it may not execute properly in command line environment.

86.I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, what’s the problem?

PHP Interpreter treats numbers beginning with 0 as octal. Look at the similar PHP interview questions for more numeric problems.

87.How can we encrypt the username and password using PHP?

You can encrypt a password with the following Mysql>SET PASSWORD=PASSWORD("Password");

88.How do you pass a variable by value?

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

89.What is the functionality of the functions STRSTR() and STRISTR()?

string strstr ( string haystack, string needle ) returns part of haystack string from the first occurrence of needle to the end of haystack. This function is case-sensitive.

stristr() is idential to strstr() except that it is case insensitive.

90.How can we send mail using JavaScript?

No. There is no way to send emails directly using JavaScript.

91.Would I use print "$a dollars" or "{$a} dollars" to print out the amount of dollars in this example?

In this example it wouldn’t matter, since the variable is all by itself, but if you were to print something like "{$a},000,000 mln dollars", then you definitely need to use the braces

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

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

93.How do I find out the number of parameters passed into function9. ?

func_num_args() function returns the number of parameters passed in.

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

95.Are objects passed by value or by reference?

Everything is passed by value.

96.WHAT ARE THE DIFFERENT TYPES OF ERRORS IN PHP?

Here are three basic types of runtime errors in PHP:

97.Are objects passed by value or by reference?

Everything is passed by value.

98.How do you call a constructor for a parent class?

parent::constructor($value)

99.What is the difference between characters \023 and \x23?

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

100.How can we create a database using PHP and mysql?

We can create MySQL database with the use of mysql_create_db($databaseName) to create a database.

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

102.How can we extract string "abc.com" from a string "mailto:info@abc.com?subject=Feedback" using regular expression of PHP?

$text = "mailto:info@abc.com?subject=Feedback";
preg_match('|.*@([^?]*)|', $text, $output);
echo $output[1];

103.What’s the difference between htmlentities() and htmlspecialchars()?

htmlspecialchars only takes care of <, >, single quote ‘, double quote " and ampersand. htmlentities translates all occurrences of character sequences that have different meaning in HTML.

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

0 comments:

Post a Comment