Tuesday, January 29, 2008

PHP Interview Questions & Answers Part 2

How can you analyse file uploading ($_FILES) in php?
You can analyse by printing the $_FILES global array using

echo "
";
print_r($_FILES);
How can we reset a cookie in php?
Reset a cookie by specifying its name only
Example: setcookie('w3answers');
Is it possible to eject a CD-ROM from a WINDOWS based OS using PHP?
Yes it is possible.We have to use PHP's COM Methods
ANS:

//create an instance of Windows Media Player
$mp = new COM("WMPlayer.OCX");
//ejects the first cd-rom on the drive list
$mp->cdromcollection->item(0)->eject();
?>

How will we disable the registering of session variables through the $_SESSION
super global ?
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
**********************************
Answer is from PHP Manual
refer session_unset function
**********************************

What is the purpose of the open_basedir directive?
A. To indicate the directory that include() calls will use as a base.
B. To restrict file open access to a specific directory.
C. To set the working directory.
D. To allow additional file open access than that granted by safe_mode.
Answer B is correct.
Answer A is incorrect because the behavior of include() is
unchanged.
Answer C is incorrect because the working directory does not depend
on open_basedir.
Answer D is incorrect because open_basedir is not affected by
whether safe_mode is enabled

Which of the following functions can be used to escape data such that it can be displayed without altering the appearance of the original data?
A. htmlspecialchars()
B. addslashes()
C. escapeshellargs()
D. urlencode()

Answer A is correct because htmlspecialchars() will convert special characters
to HTML entities that will display correctly in any Web client.
Answer B is incorrect because addslashes() only escapes single quotes.
Answer C is incorrect because escapeshellargs() is only helpful when dealing with shell command arguments.
Answer D is incorrect because URL encoding is not interpreted by
Web clients except in the context of URLs
When is cross-site scripting a heightened risk?
A. When storing data submitted by the user.
B. When displaying foreign data.
C. When executing a shell command.
D. When opening a remote URL.

Answer B is correct.
When displaying foreign data that is not properly escaped, you
can inadvertently expose your users to significant risk.
Answer A is incorrect because storing data poses no immediate threat, even though this might result in a cross-site scripting vulnerability later.
Answers C and D are incorrect because these activities are unrelated

What is the purpose of the escapeshellarg() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D To remove arguments from a shell command.

Answer A is correct.
Answers B and D are incorrect because escapeshellarg()
does not remove characters.
Answer C is incorrect because escapeshellarg()
does not attempt to solve this problem

What is the purpose of the escapeshellcmd() function?
A. To prepare data so that it can be used as a single argument in a shell command.
B. To remove malicious characters.
C. To escape metacharacters, so that they can’t be used to execute arbitrary
commands.
D. To prevent cross-site scripting attacks.

Answer C is correct.
Answer A is incorrect because escapeshellcmd() does not
attempt to solve this problem.
Answer B is incorrect because escapeshellcmd() does not actually remove characters.
Answer D is incorrect because escaping data to protect against cross-site scripting is much different than escaping data to be used in a shell command

What are the two most important practices to mitigate the risk of an SQL
injection vulnerability?
A. Disabling register_globals and enabling safe_mode.
B. Enabling safe_mode and filtering any data used in the construction of the
SQL statement.
C. Filtering and escaping any data used in the construction of the SQL statement.
D. Disabling register_globals and escaping any data used in the construction
of the SQL statement.
Answer C is correct.
With properly filtered data, escaping any metacharacters that
remain can mitigate the remaining risks.
Answers A, B, and D are incorrect because
register_globals does not directly affect the risk of SQL injection, and
safe_mode is unrelated

With register_globals enabled, which of the following practices is
particularly important?
A. Initialize all variables.
B. Filter all foreign data.
C. Escape all data used in SQL statements.
D. Escape all data prior to output.

Answer A is correct.
Answers B, C, and D are incorrect
because these practices are not dependent on
whether register_globals is enabled

The PHP date functions are only guaranteed to work for dates after _____.
A. January 1, 1970 00:00:00
B. January 1, 1900 00:00:00
C. January 1, 1963 00:00:00
D. January 18, 2038 22:14:07

The correct answer is A.
The UNIX epoch is January 1, 1970 00:00:00 UTC. On
32-bit systems, the date functions are only guaranteed
to work until January 19,2038.

Which of the following functions will output the current time as 11:26 pm?
A. print date(‘H:m a’);
B. print date(‘G:M a’);
C. print date(‘G:i a’);
D. print strftime(‘%I:%M %p’);

The correct answers are C and D

The ________ function will return the current UNIX time stamp.
The correct answer is time().

Which of the following sentences are incorrect?
A. date() returns the current UNIX datestamp.
B. date() returns a formatted date string.
C. date() requires a time stamp to be passed to it.
D. date() returns a date array.

The correct answers are A, C, and D.
date() takes a format string and an optional time stamp and produces a formatted date string. If a UNIX time stamp is not passed into date(), it will use the current time

Which of the following functions require an open file resource?
A. fgets()
B. fopen()
C. filemtime()
D. rewind()
E. reset()

The correct answers are A and D. fgets() and rewind() both act on an open file
resource. fopen() opens files to create resources, whereas filemtime() takes a filename and reset() acts on arrays

If you have an open file resource, you can read data from it one line at a time with the _____ function.
The correct answer is fgets().

Which of the following can be used to determine if a file is readable?
A. stat()
B. is_readable()
C. filetype()
D. fileowner()
E. finfo()


The correct answers are A and B.
stat() returns an array of information about a
file, including who owns it and what its permission mode is.Together these are
sufficient to tell if a file is readable.
is_readable(), as the name implies, returns
true if a file is readable.

What are the contents of output.txt after the following code snippet is run?

$str = ‘abcdefghijklmnop’;
$fp = fopen(“output.txt”, ‘w’);
for($i=0; $i< 4; $i++) {
fwrite($fp, $str, $i);
}

?>

A. abcd
B. aababcabcd
C. aababc
D. aaaa

The correct answer is C.

On the first iteration, $i is 0, so no data is written.
On the second iteration $i is 1, so a is written. On the third, ab is written,
and on the fourth abc is written.Taken together, these are aababc.

Which of the following output ‘True’?
A. if(“true”) { print “True”; }

B. $string = “true”;
if($string == 0) { print “True”; }

C. $string = “true”;
if(strncasecmp($string, “Trudeau”, 4)) { print “True”; }

D. if(strpos(“truelove”, “true”)) { print “True”; }

E. if(strstr(“truelove”, “true”)) { print “True”; }

Answers A, B, C, and E are correct.
Answer A is correct because a non-empty
string will evaluate to true inside an if() block.
Answer B is correct when comparing a string and an integer with ==, PHP will convert the string into an integer. ‘true’ converts to 0, as it has no numeric parts.
In answer C, strncasecmp() returns 1 because the first four characters of ‘Trud’ come before the first four characters of true when sorted not case sensitively.
Answer D is incorrect because strpos() returns 0 here (true matches truelove at offset 0).We could make this return True by requiring strpos() to be !== false.
:)
Answer E is correct because strstr() will return the entire string, which will evaluate to true in the if() block.

If $time = ‘Monday at 12:33 PM’; or $time = ‘Friday the 12th at 2:07
AM’; which code fragment outputs the hour (12 or 2, respectively)?
A. preg_match(‘/\S(\d+):/’, $time, $matches);
print $matches[1];
B. preg_match(‘/(\w+)\Sat\S(\d+):\d+/’, $time, $matches);
print $matches[2];
C. preg_match(‘/\s([a-zA-Z]+)\s(\w+)\s(\d+):\d+/’, $time,
$matches);
print $matches[3];
D. preg_match(‘/\s(\d+)/’, $time, $matches);
print $matches[1];
E. preg_match(‘/\w+\s(\d+):\d+/’, $time, $matches);
print $matches[1];

Answer E is correct.
Answer A and B both fail because \S matches nonwhitespace
characters, which break the match. Answer C will correctly match the first $time
correctly, but fail on the second because ‘12th’ will not match [a-zA-Z]. Answer D
matches the first, but will fail on the second, capturing the date (12) instead of the hour.
Which question will replace markup such as img=/smiley.png with
src=”/smiley.png”>?
A. print preg_replace(‘/img=(\w+)/’, ‘’, $text);
B. print preg_replace(‘/img=(\S+)/’, ‘’, $text);
C. print preg_replace(‘/img=(\s+)/’, ‘’, $text);
D. print preg_replace(‘/img=(\w)+/’, ‘’, $text);

Answer B is correct.
The characters / and . are not matched by \w (which only
matches alphanumerics and underscores), or by \s (which only matches whitespace).

Given $email = ‘bob@example.com’; which code block will output example.com?
A. print substr($email, -1 * strrpos($email, ‘@’));
B. print substr($email, strrpos($email, ‘@’));
C. print substr($email, strpos($email, ‘@’) + 1);
D. print strstr($email, ‘@’);
Answer C is correct.
strpos() identifies the position of the @ character in the string.To capture only the domain part of the address, you must advance one place to the first character after the @.

Tell me the following scripts output
$a = array (‘a’ => 20, 1 => 36, 40);
array_rand ($a);
echo $a[0];
?>
A. A random value from $a
B. ‘a’
C. 20
D. 36
E. Nothing
Only E is correct.
The $a array doesn’t have any element with a numeric key of
zero, and the array_rand() function does not change the keys of the array’s elements only their order.

Which of the following functions can be used to sort an array by its keys
in descending order?
A. sort
B. rsort
C. ksort
D. krsort
E. reverse_sort

D is correct.

The sort() and rsort() functions operate on values, whereas
ksort() sorts in ascending order and reverse_sort() is not a PHP function
Which of the following types can be used as an array key? (Select three.)
A. Integer
B. Floating-point
C. Array
D. Object
E. Boolean

Answers A, B, and E are correct.

A Boolean value will be converted to either 0 if
it is false or 1 if it is true, whereas a floating-point value will be truncated to its integer equivalent.

Arrays and objects, however, cannot be used under any circumstance
Which of the following functions allows you to store session data in a database?
A. session_start();
B. session_set_save_handler();
C. mysql_query();
D. You cannot store session data in a database.

Answer B is correct.

You can use session_set_save_handler() to override
PHP’s default session-handling functions and store session data any way you want.
Answer A is incorrect because session_start() only activates PHP sessions for
the current script. Answer C is incorrect because mysql_query() only executes a
query with MySQL and does not affect the behavior of PHP’s session mechanism.
Answer D is incorrect because this statement is false.
Why must you call session_start() prior to any output?
A. Because it is easy to forget if not placed at the top of your scripts.
B. Because you can no longer access the session data store after there has been
output.
C. Because session_start() sets some HTTP headers.
D. Because calling session_start() causes the HTTP headers to be sent.

Answer C is correct.

Answer A is incorrect because this is a technical necessity, not
a best practice. Answer B is incorrect because accessing the session data store is
completely independent of whether there has been any output. Answer D is incorrect
because you can set other HTTP headers after a call to session_start().
If you set a cookie with either setcookie() or header(), you can
immediately check to see whether the client accepted it. True or False ,comment it
A. True, you can check the $_COOKIE superglobal array to see if it contains the
value you set.
B. True, but only if register_globals is enabled.
C. False, you can only use setcookie() if you need to test for acceptance.
Using header() does not work.
D. False, you must wait until you receive another HTTP request to determine
whether it includes the Cookie header.

Answer D is correct.

The response that contains the Set-Cookie header is not sent
until PHP finishes executing, so you cannot test for acceptance prior to this.
Answers A and B are incorrect because the answer is false. Answer C is incorrect
because using setcookie() and header() both result in the same thing: A Set-
Cookie header is included in the response.

When an expiration date is given in a Set-Cookie header, what is the
resulting behavior in subsequent requests?
A. If the expiration date has expired, the cookie is not included.
B. The behavior is the same; the expiration date is included in the Cookie
header, and you can access this information in the $_COOKIE superglobal
array.
C. The cookie persists in memory until the browser is closed.
D. The cookie is deleted and therefore not included in subsequent requests.

Answer A is correct.

Answer B is incorrect because only the name and value of the
cookie are included in the Cookie header. Answer C is incorrect because setting
an expiration date causes a cookie to either be deleted (if the date has expired) or written to disk. Answer D is incorrect because the cookie is only deleted if the date has expired, which isn’t necessarily the case.

Which of the following form element names can be used to create an array
in PHP?
A. foo
B. [foo]
C. foo[]
D. foo[bar]

Answer C is correct.

PHP will create an enumerated array called foo that contains
the values of all form elements named foo[] in the HTML form.Answers A, B,
and D are incorrect because any subsequent form elements of the same name will
overwrite the value in previous elements.
When processing the form, what is the difference between a hidden form
element and a non hidden one, such as a text box?
A. The hidden form element does not have a name.
B. There is no difference.
C. The hidden form element does not have a value.
D. The hidden form element is excluded from the request.

Answer B is correct.

When processing a form, each form element is simply a
name/value pair within one of the superglobal arrays. Answers A and C are incorrect because hidden form elements can (and should) have both a name and a
value. Answer D is incorrect because hidden form elements are only excluded
from the user’s view, not from the HTTP request
Which types of form elements can be excluded from the HTTP request?
A. text, radio, and check box
B. text, submit, and hidden
C. submit and hidden
D. radio and check box

Answer D is correct.

When not selected, both radio buttons and check boxes are
excluded from the HTTP request. Answer A and B are incorrect because text
boxes are always included in the request. Answer C is incorrect because hidden
form elements are always included.
Is it possible to pass data from PHP to JavaScript?
A. No, because PHP is server-side, and JavaScript is client-side.
B. No, because PHP is a loosely typed language.
C. Yes, because JavaScript executes before PHP.
D. Yes, because PHP can generate valid JavaScript.

Answer D is correct.

JavaScript, like HTML, can be dynamically generated by
PHP. Answers A and B are incorrect because the answer is yes. Answer C is incorrect because PHP executes before JavaScript.
What will be the following script output?
error_reporting(E_ALL);
class a
{
var $c;
function a()
{
$this->c = 10;
}
}
class b extends a
{
function print_a()
{
echo $this->c;
}
}
$b = new b;
$b->print_a();

?>

A. Nothing
B. An error because b does not have a constructor
C. 10
D. NULL
E. False

Answer C is correct.

Because the class b does not have a constructor, the constructor of its parent class is executed instead.This results in the value 10 being assigned to the $c member property.
When serializing and unserializing an object, which of the following
precautions should you keep in mind? (Choose two)
A. Always escape member properties that contain user input.
B. If the object contains resource variables, use magic functions to restore the
resources upon unserialization.
C. Use the magic functions to only save what is necessary.
D. Always use a transaction when saving the information to a database.
E. If the object contains resource variables, it cannot be serialized without first destroying and releasing its resources.

Answers B and C are correct.

Whenever you design an object that is meant to be
serialized or that can contain resource objects, you should implement the appropriate magic functions to ensure that it is serialized and unserialized properly—and using the smallest amount of information possible
What will be the following script output?

class a
{
var $c;
function a ($pass)
{
$this->c = $pass;
}
function print_data()
{
echo $this->$c;
}
}
$a = new a(10);
$a->print_data();

?>

A. An error
B. 10
C. “10”
D. Nothing
E. A warning

Answer D is correct.

There actually is a bug in the print_data() function—
$this->$c is interpreted as a variable by PHP, and because the $c variable is not
defined inside the function, no information will be available for printing. Note
that if error reporting had been turned on, either through a php.ini setting or
through an explicit call to error_reporting(), two warnings would have been
outputted instead—but, unless the exam question tells you otherwise, you should
assume that the normal PHP configuration is being used. And in that case, the
interpreter is set not to report warnings.
What will be the following script output?
$a = 1;
$a = $a— + 1;
echo $a;
?>

A. 2
B. 1
C. 3
D. 0
E. Null

Answer B is correct.
Which data type will the $a variable have at the end of the following script?
$a = “1”;
echo $x;
?>

A. (int) 1
B. (string) “1”
C. (bool) True
D. (float) 1.0
E. (float) 1

Answer B is correct.

When a numeric string is assigned to a variable, it remains
a string, and it is not converted until needed because of an operation that
requires so.
What will be the following script output?
$x = 3 - 5 % 3;
echo $x;
?>
A. 2
B. 1
C. Null
D. True
E. 3

Answer B is correct.

Because of operator precedence, the modulus operation is
performed first, yielding a result of 2 (the remainder of the division of 5 by 2).
Then, the result of this operation is subtracted from the integer 3.

No comments: