PHP Interview Questions-3

PHP Interview Questions
 1.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.

2.How a constant is defined in a PHP script?

The define() directive lets us defining a constant as follows:
define (“ACONSTANT”, 123);

3.How can you pass a variable by reference?

To be able to pass a variable by reference, we use an ampersand in front of it, as follows $var1 = &$var2

4.Will a comparison of an integer 12 and a string “13? work in PHP?

“13? and 12 can be compared in PHP since it casts everything to the integer type.

5.How is it possible to cast types in PHP?

The name of the output type have to be specified in parentheses before the variable which is to be cast as follows:

* (int), (integer) – cast to integer

* (bool), (boolean) – cast to boolean

* (float), (double), (real) – cast to float

* (string) – cast to string

* (array) – cast to array

* (object) – cast to object

6.When a conditional statement is ended with an endif?

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

7.How is the ternary conditional operator used in PHP?

It is composed of three expressions: a condition, and two operands describing what instruction should be performed when the specified condition is true or false as follows:

Expression_1 ? Expression_2 : Expression_3;

8.What is the function func_num_args() used for?

The function func_num_args() is used to give the number of parameters passed into a function.

9.If the variable $var1 is set to 10 and the $var2 is set to the character var1, what’s the value of $$var2?

$$var2 contains the value 10.

10.What does accessing a class via :: means?

:: is used to access static methods that do not require object initialization.

11.In PHP, objects are they passed by value or by reference?

In PHP, objects passed by value.

12.Are Parent constructors called implicitly inside a class constructor?

No, a parent constructor have to be called explicitly as follows:

parent::constructor($value)

13.What’s the difference between __sleep and __wakeup?

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

14.What is faster?

Combining two variables as follows:

$variable1 = ‘Hello ‘;

$variable2 = ‘World’;

$variable3 = $variable1.$variable2;

15.what is the definition of a session?

A session is a logical object enabling us to preserve temporary data across multiple PHP pages.

16.How to initiate a session in PHP?

The use of the function session_start() lets us activating a session.

17.How is it possible to propagate a session id?

It is possible to propagate a session id via cookies or URL parameters.

18.What is the meaning of a Persistent Cookie?

A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.

19.When sessions ends?

Sessions automatically ends when the PHP script finishs executing, but can be manually ended using the session_write_close().

20.What is the difference between session_unregister() and session_unset()?

The session_unregister() function unregister a global variable from the current session and the session_unset() function free all session variables.

21.What does $GLOBALS means?

$GLOBALS is associative array including references to all variables which are currently defined in the global scope of the script.

22.What does $_SERVER means?

$_SERVER is an array including information created by the web server such as paths, headers, and script locations.

23.What does $_FILES means?

$_FILES is an associative array composed of items sent to the current script via the HTTP POST method.

24.What is the difference between $_FILES['userfile']['name'] and $_FILES['userfile']['tmp_name']?

$_FILES['userfile']['name'] represents the original name of the file on the client machine,
$_FILES['userfile']['tmp_name'] represents the temporary filename of the file stored on the server.

25.How can we get the error when there is a problem to upload a file?

$_FILES['userfile']['error'] contains the error code associated with the uploaded file.

26.How can we change the maximum size of the files to be uploaded?

We can change the maximum size of files to be uploaded by changing upload_max_filesize in php.ini.

27.What does $_ENV means?

$_ENV is an associative array of variables sent to the current PHP script via the environment method.

28.What does $_COOKIE means?

$_COOKIE is an associative array of variables sent to the current PHP script using the HTTP Cookies.

29.What does the scope of variables means?

The scope of a variable is the context within which it is defined. For the most part all PHP variables only have a single scope. This single scope spans included and required files as well.

30. what the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?

$a and $b:    TRUE if both $a and $b are TRUE.

$a & $b:        Bits that are set in both $a and $b are set.

31.What are the two main string operators?

The first is the concatenation operator (‘.’), which returns the concatenation of its right and left arguments. The second is (‘.=’), which appends the argument on the right to the argument on the left.

32.What does the array operator ‘===’ means?

$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

33. What is the differences between $a != $b and $a !== $b?

!= means inequality (TRUE if $a is not equal to $b) and !== means non-identity (TRUE if $a is not identical to $b).

34.How can we determine whether a PHP variable is an instantiated object of a certain class?

To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.

35.What is the goto statement useful for?

The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.

36.what is the difference between  Exception::getMessage and Exception::getLine ?

Exception::getMessage lets us getting the Exception message and Exception::getLine lets us getting the line in which the exception occurred.

37.What does the expression Exception::__toString means?

Exception::__toString gives the String representation of the exception.

38.How is it possible to parse a configuration file?

The function parse_ini_file() enables us to load in the ini file specified in filename, and returns the settings in it in an associative array.

39.How can we determine whether a variable is set?

The boolean function isset determines if a variable is set and is not NULL.

40.What is the difference between the functions strstr() and stristr()?

The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-sensitive. stristr() is identical to strstr() except that it is case insensitive.

41.what is the difference between for and foreach?

for is expressed as follows:
for (expr1; expr2; expr3)
statement
The first expression is executed once at the beginning. In each iteration, expr2 is evaluated. If it is TRUE, the loop continues and the statements inside for are executed. If it evaluates to FALSE, the execution of the loop ends. expr3 is tested at the end of each iteration.
However, foreach provides an easy way to iterate over arrays and it is only used with arrays and objects.

42.Is it possible to submit a form with a dedicated button?

It is possible to use the document.form.submit() function to submit the form. For example: <input type=button value=”SUBMIT” onClick=”document.form.submit()”>

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

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

44.Is it possible to protect special characters in a query string?

Yes, we use the urlencode() function to be able to protect special characters.

45.What are the three classes of errors that can occur in PHP?

The three basic classes of errors are notices (non-critical), warnings (serious errors) and fatal errors (critical errors).

46.What is the difference between characters \034 and \x34?

\034 is octal 34 and \x34 is hex 34.

47.How can we pass the variable through the navigation between the pages?

It is possible to pass the variables between the PHP pages using sessions, cookies or hidden form fields.

48.Is it possible to extend the execution time of a php script?

The use of the set_time_limit(int seconds) enables us to extend the execution time of a php script. The default limit is 30 seconds.

49.Is it possible to destroy a cookie?

Yes, it is possible by setting the cookie with a past expiration time.

50.What is the default session time in php?

The default session time in php is until closing of browser

51.Is it possible to use COM component in PHP?

Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.

52.Would you initialize your strings with single quotes or double quotes?

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.

53.How can we extract string ‘abc.com ‘ from a string http://info@abc.com using regular expression of php?

We can use the preg_match() function with “/.*@(.*)$/” as
the regular expression pattern. For example:
preg_match(“/.*@(.*)$/”,”http://info@abc.com”,$data);
echo $data[1];

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

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

55.How come the code works, but doesn’t for two-dimensional array of mine?

Any time you have an array with more than one dimension, complex parsing syntax is required. print “Contents: {$arr[1][2]}” would’ve worked.

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

session_register($session_var);
$_SESSION['var'] = ‘value’;

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

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

58.With a heredoc syntax, do I get variable substitution inside the heredoc contents?

Yes.

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

We can use a simple JavaScript code linked to an event trigger of any form field. In the JavaScript code, we can call the document.form.submit() function to submit the form. For example: <input type=button value=”Save” onClick=”document.form.submit()”>

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

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

62.Can we use include (“abc.php”) two times in a php page “makeit.php”?

Yes.
For printing out strings, there are echo, print and printf. Explain the differences.
echo is the most primitive of them, and just outputs the contents following the construct to the screen. print is also a construct (so parentheses are optional when calling it), but it returns TRUE on successful output and FALSE if it was unable to print out the string. However, you can pass multiple parameters to echo, like:

<?php echo ‘Welcome ‘, ‘to’, ‘ ‘, ‘techpreparations!’; ?>

and it will output the string “Welcome to techpreparations!” print does not take multiple parameters. It is also generally argued that echo is faster, but usually the speed advantage is negligible, and might not be there for future versions of PHP. printf is a function, not a construct, and allows such advantages as formatted output, but it’s the slowest way to print out data out of echo, print and printf.

63.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().

64.What’s the output of the ucwords function in this example?

$formatted = ucwords(“TECHPREPARATIONS IS COLLECTION OF INTERVIEW QUESTIONS”);
print $formatted;
What will be printed is TECHPREPARATIONS IS COLLECTION OF 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.
16- 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.

65. 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];
Note that the second index of $output, $output[1], gives the match, not the first one, $output[0].

66.So 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.

67.How can we destroy the session, how can we unset the variable of a session?
session_unregister() – Unregister a global variable from the current session
session_unset() – Free all session variables

68.What are the different functions in sorting an array?

Sorting functions in PHP:
asort()
arsort()
ksort()
krsort()
uksort()
sort()
natsort()
rsort()

69.How can we know the count/number of elements of an array?
2 ways:
a) sizeof($array) – This function is an alias of count()
b) count($urarray) – This function returns the number of elements in an array.
Interestingly if you just pass a simple var instead of an array, count() will return 1.

70.How many ways we can pass the variable through the navigation between the pages?

At least 3 ways:

1. Put the variable into session in the first page, and get it back from session in the next page.
2. Put the variable into cookie in the first page, and get it back from the cookie in the next page.
3. Put the variable into a hidden form field, and get it back from the form in the next page.

71.What is the difference between CHAR and VARCHAR data types?

CHAR is a fixed length data type. CHAR(n) will take n characters of storage even if you enter less than n characters to that column. For example, “Hello!” will be stored as “Hello! ” in CHAR(10) column.VARCHAR is a variable length data type. VARCHAR(n) will take only the required storage for the actual number of characters entered to that column. For example, “Hello!” will be stored as “Hello!” in VARCHAR(10) column.

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

AES_ENCRYPT() and AES_DECRYPT()
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.

73.What is the functionality of MD5 function in PHP?

string md5(string)
It calculates the MD5 hash of a string. The hash is a 32-character hexadecimal number.

74.How can I load data from a text file into a table?

The MySQL provides a LOAD DATA INFILE command. You can load data from a file. Great tool but you need to make sure that:
a) Data must be delimited
b) Data fields must match table columns correctly

75.What is meant by MIME?

MIME is Multipurpose Internet Mail Extensions is an Internet standard for the format of e-mail. However browsers also uses MIME standard to transmit files. MIME has a header which is added to a beginning of the data. When browser sees such header it shows the data as it would be a file (for example image)
Some examples of MIME types:
audio/x-ms-wmp
image/png
application/x-shockwave-flash

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

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

77.What are the differences between  mysql_fetch_array(),  mysql_fetch_object(),  mysql_fetch_row()?

mysql_fetch_array() -> Fetch a result row as a combination of associative array and regular array.
mysql_fetch_object() -> Fetch a result row as an object.
mysql_fetch_row() -> Fetch a result set as a regular array().

78 If we login more than one browser windows at the same time with same user and after that we close one window, then is the session is exist to other windows or not? And if yes then why? If no then why?

Session depends on browser. If browser is closed then session is lost. The session data will be deleted after session time out. If connection is lost and you recreate connection, then session will continue in the browser.

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

80.Can we use include(abc.PHP) two times in a PHP page makeit.PHP”?

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

81.What is meant by nl2br()?

nl2br() inserts a HTML tag <br> before all new line characters \n in a string.
echo nl2br(“god bless \n you”);

output:
god bless<br>
you

82.In how many ways we can retrieve data in the result set of MYSQL using PHP?

mysql_fetch_array – Fetch a result row as an associative array, a numeric array, or both
mysql_fetch_assoc – Fetch a result row as an associative array
mysql_fetch_object – Fetch a result row as an object
mysql_fetch_row —- Get a result row as an enumerated array

83.What are the functions for IMAP?

imap_body – Read the message body
imap_check – Check current mailbox
imap_delete – Mark a message for deletion from current mailbox
imap_mail – Send an email message

85.What are encryption functions in PHP?

CRYPT()
MD5()

86.What is the difference between htmlentities() and htmlspecialchars()?

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

87.What is the functionality of the function htmlentities?

htmlentities() – Convert all applicable characters to HTML entities
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.

88.How can we get the properties (size, type, width, height) of an image using php image functions?

To know the image size use getimagesize() function
To know the image width use imagesx() function
To know the image height use imagesy() function

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

By the use of void set_time_limit(int seconds)
Set the number of seconds a script is allowed to run. If this is reached, the script returns a fatal error. The default limit is 30 seconds or, if it exists, the max_execution_time value defined in the php.ini. If seconds is set to zero, no time limit is imposed.When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

90. How to set cookies?

setcookie(‘variable’,'value’,'time’)
;
variable – name of the cookie variable
value – 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

91.What’s PHP ?

The PHP Hypertext Preprocessor is a programming language that allows web developers to create dynamic content that interacts with databases. PHP is basically used for developing web based software applications.

92.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.Sessions are commonly used to store temporary data to allow multiple PHP pages to offer a complete functional transaction for the same visitor.

93.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’;

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

95.How do you define a constant?

Via define() directive, like define (“MYCONSTANT”, 100);

95.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.But require() and include() will do it as many times they are asked to do.

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

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

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

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

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

101.How can we send mail using JavaScript?

No. There is no way to send emails directly using JavaScript.
But you can use JavaScript to execute a client side email program send the email using the “mailto” code. Here is an example:
function myfunction(form)
{
tdata=document.myform.tbox1.value;
location=”mailto:mailid@domain.com?subject=…”;
return true;
}

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

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

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

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

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

0 comments:

Post a Comment