PHP Interview questions -4

PHP Interview questions -4

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 = "";
The output is "". 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:
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 time
For Example:
If you set to 0 you say that there is not limit.

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

7.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 it
was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename
given by destination.
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.

8.How do you insert single & double quotes in MySQL db without using PHP?

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

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

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

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

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

13.What is difference between srand & shuffle?

The srand function seeds the random number generator with seed and shuffle is used for shuffling the array
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
reordering the keys.srand - Seed the random number generator

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

array_unique() funciton can be used for the purpose.

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

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

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

SELECT MAX(ID) from tablename;

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

Select * from tablename LIMIT 0, 5;

18.How to store binary data in MySQL?

Use BLOB data type for the database field.

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

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

20.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.
Page 4/8
PDF generated by PHPKB Knowledge Base Script
mysql_fetch_row - fetches a result row as array.

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

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

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

24.How I can get IP address?


25.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 revealed
to be Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/418 (KHTML, like Gecko) Safari/417.9.3
when visiting a PHP page.
This can be useful to programmers if they are using special features that may not work for everyone, or if
they want to get an idea of their target audience. This also is important when using the get_browser() function
for finding out more information about the browser's capabilities. By having this information the user can be
directed 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 the
browser's information in the browscap.ini file.
echo $_SERVER['HTTP_USER_AGENT'] . "<hr />\n";
$browser = get_browser();
foreach ($browser as $name => $value)
echo "<b>$name</b> $value <br />\n";
Page 5/8
PDF generated by PHPKB Knowledge Base Script

26.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 functionsfor 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().

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

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

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

30.What is meant by nl2br()?

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

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

32.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
string urldocode(str)
This will simple decode the GET variable’s value. Example: echo (urldecode($_GET_VARS[var])) will output
“hello world”

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

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

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

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

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

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

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

38.Can you tell me the difference between include and require functions?

Both these functions differ in how they handle failures that occur. Suppose a file is not found by the include() function, then it will simply give a warning and script execution will not be interrupted. However, if a file is not found using a require() function, it will throw up a fatal warning and stop the script execution.

39.What is a CAPTCHA and when do you use it?

CAPTCHA is the short form of Completely Automated Public Turing Test. It’s a step taken to ensure that a feature is not abused in a way it’s not meant to be used. We use CAPTCHAS for general form submissions, registrations, user generated content and so on to prevent spam bots from clogging up the system or spamming.

40.What is the difference between GET and POST functions?

GET function is normally used when the result of using this function does not cause any visible change on the state of the world. This is normally used in cases like searching from a database where no changes are made to the system.POST function is used when there is a visible change on the state of the world. When we use a POST function, normally the system changes. E.g. when we add, delete or modify values from a database. A simple example is a form submission.

41.Is it possible to know details about the browser being used to view a PHP website?

Yes. We can use the get_browser() function to get the details of the browser a user is using. This information is usually found inside the browscap.ini file.

42.Is it possible to create a database using PHP and MySQL?

Yes. We can create a database using the function mysql_create_db(“<Insert database name here>”).

43.How many times is it possible to use an include function in a PHP page?

We can use include function multiple times in any dynamically generated PHP page. However, it’s not considered a good practice to have multiple include functions on the same page.

44.Can you tell me whether objects are passed by value or by reference?

In PHP, everything is usually passed by value and not by reference.

45.What is an efficient way to combine two variables in PHP?

There are two different ways to combine variables in PHP. Let’s take an example.

    $var1 = ‘Hello ‘;
    $var2 = ‘World’;

We can combine it using the two codes below

    $var 3 = $var1.$var2; and
    $var3 = “$var1$var2?;

It’s usually seen that, for large datasets, the first method outperforms the second one

46.What does PEAR stands for?

PEAR means “PHP Extension and Application Repository”. it extends PHP and provides a higher level of programming for web developers.

47. What is the actually used PHP version?

Version 5 is the actually used version of PHP.

48.How do you execute a PHP script from the command line?

Just use the PHP command line interface (CLI) and specify the file name of the script to be executed as follows:


php script.php


49.How to run the interactive PHP shell from the command line interface?

Just use the PHP CLI program with the option -a as follows:


php -a


50. What are the correct and the most two common way to start and finish a PHP block of code?

The two most  common ways to start and finish a PHP script are: <?php [   ---  PHP code---- ] ?> and <? [---  PHP code  ---] ?>

51.How can we display the output directly to the browser?

To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.

52.What is the main difference between PHP 4 and PHP 5?

PHP 5 presents many additional OOP (Object Oriented Programming) features.

53.Is multiple inheritance supported in PHP?

PHP includes only single inheritance, it means that a class can be extended from only one single class using the keyword ‘extended’.

54.What is the meaning of a final class and a final method?

‘final’ is introduced in PHP5. Final class means that this class cannot be extended and a final method cannot be overrided.

55.How comparison of objects is done in PHP5?

We use the operator ‘==’ to test is two object are instanced from the same class and have same attributes and equal values. We can test if two object are refering to the same instance of the same class by the use of the identity operator ‘===’.

56.How can PHP and HTML interact?

It is possible to generate HTML through PHP scripts, and it is possible to pass informations from HTML to PHP.

57.What type of operation is needed when passing values through a form or an URL?

If we would like to pass values througn a form or an URL then we need to encode and to decode them using htmlspecialchars() and urlencode().

58.How can PHP and Javascript interact?

PHP and Javascript cannot directly interacts since PHP is a server side language and Javascript is a client side language. However we can exchange variables since PHP is able to generate Javascript code to be executed by the browser and it is possible to pass specific variables back to PHP via the URL.

59.What is needed to be able to use image function?

GD library is needed to be able execute image functions.

60.What is the use of the function ‘imagetypes()’?

imagetypes() gives the image format and types supported by the current version of GD-PHP.

61.What are the functions to be used to get the image’s properties (size, width and height)?

The functions are getimagesize() for size, imagesx() for width and imagesy() for height.

62.How failures in execution are handled with include() and require() functions?

If the function require() cannot access to the file then it ends with a fatal error. However, the include() function gives a warning and the PHP script continues to execute.

63.What is the main difference between require() and require_once()?

require() and require_once() perform the same task except that the second function checks if the PHP script is already included or not before executing it.

(same for include_once() and include())

64.How can I display text with a PHP script?

Two methods are possible:

<!–?php echo "Method 1"; print "Method 2"; ?–>

65.How can we display information of a variable and readable by human with PHP?

To be able to display a human-readable result we use print_r().

66.How is it possible to set an infinite execution time for PHP script?

The set_time_limit(0) added at the beginning of a script sets to infinite the time of execution to not have the PHP error ‘maximum execution time exceeded’.It is also possible to specify this in the php.ini file.

67.What does the PHP error ‘Parse error in PHP – unexpected T_variable at line x’ means?

This is a PHP syntax error expressing that a mistake at the line x stops parsing and executing the program.

68.What should we do to be able to export data into an Excel file?

The most common and used way is to get data into a format supported by Excel. For example, it is possible to write a .csv file, to choose for example comma as separator between fields and then to open the file with Excel.

69.What is the function file_get_contents() usefull for?

file_get_contents() lets reading a file and storing it in a string variable.

70.How can we connect to a MySQL database from a PHP script?

To be able to connect to a MySQL database, we must use mysql_connect() function as follows:

<!–?php $database = mysql_connect("HOST", "USER_NAME", "PASSWORD"); mysql_select_db("DATABASE_NAME",$database); ?–>

71.What is the function mysql_pconnect() usefull for?

mysql_pconnect() ensure a persistent connection to the database, it means that the connection do not close when the the PHP script ends.

72.How the result set of Mysql be handled in PHP?

The result set can be handled using mysql_fetch_array, mysql_fetch_assoc, mysql_fetch_object or mysql_fetch_row.

73.How is it possible to know the number of rows returned in result set?

The function mysql_num_rows() returns the number of rows in a result set.

74.Which function gives us the number of affected entries by a query?

mysql_affected_rows() return the number of entries affected by an SQL query.

75.What is the difference between mysql_fetch_object() and mysql_fetch_array()?

The mysql_fetch_object() function collects the first single matching record where mysql_fetch_array() collects all matching records from the table in an array.

76.How can we access the data sent through the URL with the GET method?

In order to access the data sent via the GET method, we you use $_GET array like this:
$variable = $_GET["var"]; this will now contain ‘value’

77.How can we access the data sent through the URL with the POST method?

To access the data sent this way, you use the $_POST array.

Imagine you have a form field called ‘var’ on the form, when the user clicks submit to the post form, you can then access the value like this:

78.How can we check the value of a given variable is a number?

It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.

79.How can we check the value of a given variable is alphanumeric?

It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.

80.How do I check if a given variable is empty?

If we want to check whether a variable has a value or not, it is possible to use the empty() function.

81.What does the unlink() function means?

The unlink() function is dedicated for file system handling. It simply deletes the file given as entry.

82.What does the unset() function means?

The unlink() function is dedicated for variable management. It will make a variable undefined.

83.How do I escape data before storing it into the database?

addslashes function enables us to escape data before storage into the database.

84.How is it possible to remove escape characters from a string?

The stripslashes function enables us to remove the escape characters before apostrophes in a string.

85.How can we automatically escape incoming data?

We have to enable the Magic quotes entry in the configuration file of PHP.

86.What does the function get_magic_quotes_gpc() means?

The function get_magic_quotes_gpc() tells us whether the magic quotes is switched on or no.

87.Is it possible to remove the HTML tags from data?

The strip_tags() function enables us to clean a string from the HTML tags.

88.what is the static variable in function useful for?

A static variable is defined within a function only the first time and its value can be modified during function calls as follows:

<!–?php function testFunction() { static $testVariable = 1; echo $testVariable; $testVariable++; } testFunction();        //1 testFunction();        //2 testFunction();        //3 ?–>

89.How can we define a variable accessible in functions of a PHP script?

This feature is possible using the global keyword.

90.How is it possible to return a value from a function?

A function returns a value using the instruction ‘return $value;’.

91.What is the most convenient hashing method to be used to hash passwords?

It is preferable to use crypt() which natively supports several hashing algorithms or the function hash() which supports more variants than crypt() rather than using the common hashing algorithms such as md5, sha1 or sha256 because they are conceived to be fast. hence, hashing passwords with these algorithms can vulnerability.

92.Which cryptographic extension provide generation and verification of digital signatures?

The PHP-openssl extension provides several cryptographic operations including generation and verification of digital signatures.

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

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

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

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

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

session_destroy and session_unset

96.How can we destroy the cookie?

Set same the cookie in past

97.Explain about PHP looping?

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

98.What is triggers ? Does MySQL supports it ?

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

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

100.How to set cookies in PHP?

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

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

By default the maximum size is 2MB. and we can change the following
setup at php.iniupload_max_filesize = 2M
102.How can we increase the execution time of a PHP script?

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


Post a Comment