• Like
  • Save
Zend Certification PHP 5 Sample Questions
Upcoming SlideShare
Loading in...5
×
 

Zend Certification PHP 5 Sample Questions

on

  • 11,564 views

Zend Certification PHP 5 Sample Questions

Zend Certification PHP 5 Sample Questions

Statistics

Views

Total Views
11,564
Views on SlideShare
11,551
Embed Views
13

Actions

Likes
7
Downloads
623
Comments
1

2 Embeds 13

http://www.linkedin.com 12
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Zend Certification PHP 5 Sample Questions Zend Certification PHP 5 Sample Questions Document Transcript

    • Zend Certification PHP 5 Sample Questions Email : jagat21@gmail.com Twitter : @phpknight Author : Jagat Kothari Page 1
    • Which of the following is not a valid default stream wrapper for PHP 5, assuming OpenSSL is enabled? Answer... ftps:// ftp:// sftp:// - Correct Answer https:// http:// Creating new nodes in XML documents using PHP can be done using which XML/PHP 5 technologies? Answers: (choose 2) XQuery XPath SimpleXML - Correct Answer DOM - Correct Answer SAX In PHP 5, the ________ method is automatically called when the object is created, while the _______ method is automatically called when the object is destroyed. What is the output of the following? <?php $a = 20; Author : Jagat Kothari Page 2
    • function myfunction($b) { $a = 30; global $a, $c; return $c = ($b + $a); } print myfunction(40) + $c; ?> Answer... 120 - Correct Answer Syntax Error 60 70 What is the output of the following? <?php function 1dotEach($n) { if ($n > 0) { Author : Jagat Kothari Page 3
    • 1dotEach(--$n); echo "."; }else { return $n; } } 1dotEach(4); ?> Answer... ...0 Parse Error: Syntax Error - Correct Answer ..... .... ... The ______ pattern is extremely useful for creating objects which watch the state of other objects and respond to those changes. When comparing two strings, which of the following is acceptable? Answers: (choose 4) $a === $b; - Correct Answer strcasecmp($a, $b); - Correct Answer strcmp($a, $b); - Correct Answer $a == $b; - Correct Answer str_compare($a,$b); Author : Jagat Kothari Page 4
    • What combination of boolean values for $a, $b, $c, and $d will result in the variable $number being equal to 3? <?php $a = null; $b = null; $c = null; $d = null; if($a && !$b) { if(!!$c && !$d) { if($d && ($a || $c)) { if(!$d && $b) { $number = 1; } else { $number = 2; } } else { $number = 3; } } else { $number = 4; } } else { $number = 5; Author : Jagat Kothari Page 5
    • } ?> Answer... false, true, true, true true, false, true, false - Correct Answer true, true, false, false false, true, true, false false, false, true, false If you would like to store your session in the database, you would do which of the following? Answer... It requires a custom PHP extension to change the session handler Implement the session_set_save_handler() function - Correct Answer Create functions for each session handling step and use session_set_save_handler() to override PHP's internal settings Configure the session.save_handler INI directive to your session class What is the output of the following code? <?php $string = "14302"; $string[$string[2]] = "4"; Author : Jagat Kothari Page 6
    • print $string; ?> Answer... 14304 14342 - Correct Answer 44302 14402 Array To ensure that a given object has a particular set of methods, you must provide a method list in the form of an ________ and then attach it as part of your class using the ________ keyword. Answer... array, interface interface, implements - Correct Answer interface, extends instance, implements access-list, instance Using flock() to lock a stream is only assured to work under what circumstances? Answer... When running in a Linux environment local filesystem When accessing the stream of the local filesystem When running in a Windows environment and accessing a share Author : Jagat Kothari Page 7
    • When accessing a bi-directional stream When accessing a read-only stream Which of the following operations must occur prior to any output being sent to the client (assume output buffering is disabled). Answers: (choose 3) Modifying Session Data Processing GET or POST data Manipulating Cookie data Starting a Session Sending HTTP Headers What is wrong with the following code? <?php function duplicate($obj) { $newObj = $obj; return $newObj; } $a = new MyClass(); $a_copy = duplicate($a); $a->setValue(10); Author : Jagat Kothari Page 8
    • $a_copy->setValue(20); ?> Answer... You must use return &$newObj instead There is nothing wrong with this code duplicate() must accept its parameter by reference You must use the clone operator to make a copy of an object duplicate() must return a reference What is the best measure one can take to prevent a cross-site request forgery? Answer... Disallow requests from outside hosts Add a secret token to all form submissions Turn off allow_url_fopen in php.ini Filter all output - Correct Answer Filter all input What is the best measure one can take to prevent a cross-site request forgery? Answer... Disallow requests from outside hosts Add a secret token to all form submissions Turn off allow_url_fopen in php.ini Filter all output - Correct Answer Author : Jagat Kothari Page 9
    • Filter all input Consider the following PHP script fragment: <?php $title = $dom->createElement('title'); $node = ???????? $title->appendChild($node); $head->appendChild($title); ?> What should ??????? be replaced with to add a <title> node with the value of Hello, World! Answer... $dom->createTextNode("Hello, World"); $dom->appendElement($title, "text", "Hello, world!"); $dom->appendTextNode($title, "Hello, World!"); $dom->createElement('text', "Hello, World"); None of the above What is the output of the following? Author : Jagat Kothari Page 10
    • <?php function byRef(&$number) { $number *= 10; return ($number - 5); } $number = 10; $number = byRef($number); echo $number; ?> Answer... 50 5 95 - Correct 10 100 Consider the following PHP string representing an SQL statement: $query = "UPDATE users SET password='$password' WHERE username='$username'"; Which of the following values for $username or $password would change the behavior of this query when executed? Answer... Author : Jagat Kothari Page 11
    • None of the above $username = "foobar' WHERE username='admin'"; $password = "foobar' WHERE username='admin' --:"; $username = "foobar' WHERE username='admin'"; $password = ""foobar" WHERE username="admin""; Consider the following example XML document: <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> Moved to <<a href="http://example.org/">http://www.example.org/</a>.> <br> </p> </body> </html> What is wrong with this document, and how can it be corrected? Author : Jagat Kothari Page 12
    • Answers: (choose 2) The document is completely valid All special XML characters must be represented as entities within the content of a node All tags must be closed You cannot specify a namespace for the <html> attribute The DOCTYPE declaration is malformed Which string does the following PCRE regular expression match? $regex = "/^([a-z]{5})[1-5]+([a-z]+)/"; Answers: (choose 2) None of the above Hello34262343goodbye frank12345abc hello34212343goodbye abcdefghi12345abc The following code snippet displays what for the resultant array? <?php $a = array(1 => 0, 3 => 2, 4 => 6); $b = array(3 => 1, 4 => 3, 6 => 4); print_r(array_intersect($a, $b)); Author : Jagat Kothari Page 13
    • ?> Answer... 1 => 0 1 => 3, 3 => 1, 4 => 3 3 => 1, 3=> 2, 4 => 3, 4=> 6 1 => 0, 3 => 2, 4 => 6 An empty Array - correct What is the output of this code snippet? <?php $a = array(0.001 => 'b', .1 => 'c'); print_r($a); ?> Answer... An empty array 0.001 => 'b', .1 => c 0 => 'c' '0.001' => 'b', '0.1' => c' A Syntax Error Author : Jagat Kothari Page 14
    • What is the best approach for converting this string: $string = "a=10&b[]=20&c=30&d=40+50"; Into this array? array(4) { ["a"]=> string(2) "10" ["b"]=> array(1) { [0]=> string(2) "20" } ["c"]=> string(2) "30" ["d"]=> string(5) "40 50" } The following is a common XML structure used in service oriented architectures, what does it represent? <?xml version="1.0"?> <methodCall> Author : Jagat Kothari Page 15
    • <methodName>myMethod</methodName> <params> <param> <value><string>HI!</string></value> </param> </params> </methodCall> Answer... None of the above A fragment of a complete SOAP request XML-RPC REST SOAP Consider the following simple PHP script: <?php $dom = new DomDocument(); $dom->load('test.xml'); $xpath = new DomXPath($dom); $nodes = $xpath->query(???????, $dom->documentElement); echo $nodes->item(0)->getAttributeNode('bgcolor')->value . "n"; ?> Author : Jagat Kothari Page 16
    • What XPath query should go in the ?????? above to display the "bgcolor" attribute of the first "body" node in the XML document? Answer... "*[local-name()='body']" "/body[0]/text" "/body/body[0]" "name='body'" "*[lname()='body']" What is wrong with the following code snippet? Assume default configuration values apply. <?php $fp = fsockopen('www.php.net', 80); fwrite($fp, "GET / HTTP/1.0rnHost: www.php.netrn"); $data = fread($fp, 8192); ?> Answer... The request is blocking and may cause fread() to hang The HTTP request is malformed This script should be re-written using fgets() instead of fread() The request is non-blocking and fread() may miss the response You cannot use fwrite() with fsockopen() Author : Jagat Kothari Page 17
    • Given the string: $var = "john@php.net"; Which of the following will extract the TLD (top level domain) of ".net" from the string? Answer... strstr($var, strpos($var, ".")); substr($var, strpos($var, "@")); substr($var, strstr($var, ".")); substr($var, strpos($var, ".") + 1); substr($var, strpos($var, ".")); Consider the following script: <?php try { $dbh = new PDO("sqlite::memory:"); } catch(PDOException $e) { print $e->getMessage(); } $dbh->query("CREATE TABLE foo(id INT)"); $stmt = $dbh->prepare("INSERT INTO foo VALUES(:value)"); $value = null; Author : Jagat Kothari Page 18
    • $data = array(1,2,3,4,5); $stmt->bindParam(":value", $value); /* ?????? */ try { foreach($data as $value) { /* ????? */ } } catch(PDOException $e) { /* ??????? */ } /* ?????? */ ?> What lines of code need to go into the missing places above in order for this script to function properly and insert the data into the database safely? What is the output of the following code? <?php function x10(&$number) $number *= 10; $count = 5; Author : Jagat Kothari Page 19
    • x10($count); echo $count; ?> Answer... Error: Unexpected T_VARIABLE 10 Notice regarding pass by reference 50 5 ================================================================================== ========== In PHP 5's object model, a class can have multiple ______ but only a single direct ________. Answer... None of the above interfaces, child children, interface interfaces, parent parents, interface How can one take advantage of the time waiting for a lock during a stream access, to do other tasks using the following locking code as the base: Author : Jagat Kothari Page 20
    • $retval = flock($fr, LOCK_EX); Answer... Use flock_lazy() instead of flock() Use LOCK_EX|LOCK_NB instead of LOCK_EX Use LOCK_UN instead of LOCK_EX Check the value of $retval to see if the lock was obtained Check to see if $retval == LOCK_WAIT In the MVC pattern. a request is dispatched to one or more controllers in a controller chain. This pattern is an example of which of the following design patterns? Answer... None of the above The MVC Pattern The Chain of Command/Responsibility Pattern The Dispatcher Pattern The Controller Pattern Which function would you use to add an element to the beginning of an array? Answer... array_shift() array_push(); $array[0] = "value"; array_unshift() array_pop(); Author : Jagat Kothari Page 21
    • What is the output of the following code block? <?php$a = "The quick brown fox jumped over the lazy dog.";$b = array_map("strtoupper", explode(" ", $a));foreach($b as $value) { print "$value ";}?> Answer... THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG. A PHP Error The quick brown fox jumped over the lazy dog. Array Array Array Array Array Array Array Array Array the quick brown fox jumped over the lazy dog. Given the string: $var = "john@php.net"; Which of the following will extract the TLD (top level domain) of ".net" from the string? Answer... strstr($var, strpos($var, ".")); substr($var, strpos($var, "@")); substr($var, strstr($var, ".")); substr($var, strpos($var, ".") + 1); substr($var, strpos($var, ".")); Which of the following are valid PHP variables? Author : Jagat Kothari Page 22
    • Answers: (choose 4) @$foo &$variable ${0x0} $variable $0x0 Which from the following list is not an approrpiate use of an array? Answers: (choose 1) As a list All of these uses are valid As a Lookup Table A Stack As a hash table When using a function such as strip_tags, are markup-based attacks still possible? Answer... No, HTML does not pose any security risks Yes, even a <p> HTML tag is a security risk Yes, attributes of allowed tags are ignored No, strip_tags will prevent any markup-based attack The ______ keyword is used to indicate an incomplete class or method, which must be further extended and/or implemented in order to be used. Author : Jagat Kothari Page 23
    • Answer... final protected incomplete abstract implements What XML technology is used when you mix two different document types in a single XML document? Answer... Validators DTD Transformations Namespaces How does one create a cookie which will exist only until the browser session is terminated? Answer... You cannot create cookies that expire when the browser session is terminated Setting the expiration time for a cookie to a time in the distant future Do not provide a cookie expiration time Enable Cookie Security Set a cookie without a domain What are the values of $a in $obj_one and $obj_two when this script is executed? Author : Jagat Kothari Page 24
    • <?phpclass myClass { private $a; public function __construct() { $this->a = 10; } public function printValue() { print "The Value is: {$this->a}n"; } public function changeValue($val, $obj = null) { if(is_null($obj)) { $this->a = $val; } else { $obj->a = $val; } } public function getValue() { return $this->a; }}$obj_one = new myClass();$obj_two = new myClass();$obj_one- >changeValue(20, $obj_two);$obj_two->changeValue($obj_two->getValue(), $obj_one);$obj_two- >printValue();$obj_one->printValue();?> Answer... 10,20 You cannot modify private member variables of a different class 20,20 10,10 20,10 Which of the following extensions are no longer part of PHP 5 and have been moved to PECL? Answers: (choose 2) tidy mysql w32api curl dio What is the output of this code snippet? Author : Jagat Kothari Page 25
    • <?php$a = array(0.001 => 'b', .1 => 'c');print_r($a);?> Answer... An empty array 0.001 => 'b', .1 => c 0 => 'c' '0.001' => 'b', '0.1' => c' A Syntax Error In PHP 4 you could iterate over every member property of an object using foreach(), in PHP 5 to accomplish the same task on a non-public array you could use the ___________ interface. ArrayIterator Which of the following is not a valid default stream wrapper for PHP 5, assuming OpenSSL is enabled? Answer... ftps:// ftp:// sftp:// https:// http:// Consider the following code: <?phpheader("Location: {$_GET['url']}");?> Which of the following values of $_GET['url'] would cause session fixation? Author : Jagat Kothari Page 26
    • Answers: (choose 1) Session Fixation is not possible with this code snippet http://www.zend.com/?PHPSESSID=123 PHPSESSID%611243 Set-Cookie%3A+PHPSESSID%611234 http%3A%2F%2Fwww.zend.com%2F%0D%0ASet-Cookie%3A+PHPSESSID%611234 Which of the following comparisons will evaluate to true? Answers: (choose 3) 't' == t 1 === "1time" "top" == 0 "top" === 0 1 == "1time" Which of the following functions are part of PHP's internal Iterator interface? Answers: (choose 5) rewind() valid() next() key() current() <?phpclass A { public function bar() { print "Hello"; }}class B extends A { function bar() { print "Goodbye"; }}$c = new B();$c->bar();?> Author : Jagat Kothari Page 27
    • Goodbye Why is it important from a security perspective to never display PHP error messages directly to the end user, yet always log them? Answers: (choose 2) Error messages will contain sensitive session information Error messages can contain cross site scripting attacks Security risks involved in logging are handled by PHP Error messages give the perception of insecurity to the user Error messages can contain data useful to a potential attacker Consider the following script: <?phptry { $dbh = new PDO("sqlite::memory:");} catch(PDOException $e) { print $e->getMessage();} $dbh->query("CREATE TABLE foo(id INT)");$stmt = $dbh->prepare("INSERT INTO foo VALUES(:value)");$value = null;$data = array(1,2,3,4,5);$stmt->bindParam(":value", $value);/* ?????? */try { foreach($data as $value) { /* ????? */ }} catch(PDOException $e) { /* ??????? */}/* ?????? */?> What lines of code need to go into the missing places above in order for this script to function properly and insert the data into the database safely? Answers: (choose 4) $dbh->beginTransaction(); $dbh->commit(); $stmt->execute(); Author : Jagat Kothari Page 28
    • $dbh->rollback(); $dbh->query($stmt); What is the output of the following? <?phpfunction byRef(&$apples){ $apples++;}$oranges = 5;$apples = 5;byRef($oranges);echo "I have $apples apples and $oranges oranges";?> Answer... I have 6 apples and 6 oranges I have 6 apples and 5 oranges I have 5 apples and 6 oranges I have 5 apples and 5 oranges Creating new nodes in XML documents using PHP can be done using which XML/PHP 5 technologies? Answers: (choose 2) XQuery XPath SimpleXML DOM SAX To ensure that a given object has a particular set of methods, you must provide a method list in the form of an ________ and then attach it as part of your class using the ________ keyword. Answer... Author : Jagat Kothari Page 29
    • array, interface interface, implements interface, extends instance, implements access-list, instance When working with a database, which of the following can be used to mitigate the possibility of exposing your database credientials to a malicious user? Answers: (choose 3) Moving all database credentials into a single file Moving all database credentials outside of the document root Restricting access to files not designed to be executed independently Setting creditial information as system environment variables Using PHP constants instead of variables to store credentials To force a user to redirect to a new URL from within a PHP 5 script, which of the following should be used? Answer... Send a HTTP "Location:" header Use the HTML <redirect> Tag Send a HTTP "Forward:" header Use the redirect() function A fingerprint of a string can be determined using which of the following? Author : Jagat Kothari Page 30
    • Answer... md5() hash() fingerprint() None of the above What is the difference between the include and require language constructs? Answer... Require constructs can't be used with URL filenames Include constructs cause a fatal error if the file doesn't exist There is no difference other than the name Include constructs are processed at run time; require constructs are processed at compile time Require constructs cause a fatal error if the file can't be read What reproduces the same behavior in PHP 5 as the following PHP 4 code snippet: <?php$a = new Foo();$b = $a;?> Answer... $b must be copied to $a completely using the clone operator The code remains unchanged in both PHP 4 and PHP 5 Set $b to a new instance of the Foo Class This code throws a fatal error in PHP 5 $a must be copied using the clone operatior, and $a must be copied completely to $b using the clone operator Author : Jagat Kothari Page 31
    • What is the output of the following PHP script? <?php$a = 1;$b = 2.5;$c = 0xFF;$d = $b + $c;$e = $d * $b;$f = ($d + $e) % $a;print ($f + $e);?> Which statement will return the third parameter passed to a function? Answer... $argv[3]; $argv[2]; func_get_args(3); func_get_arg(2); func_get_arg(3); What is the best way to iterate and modify every element of an array using PHP 5? Answer... You cannot modify an array during iteration for($i = 0; $i < count($array); $i++) { /* ... */ } foreach($array as $key => &$val) { /* ... */ } Author : Jagat Kothari Page 32
    • foreach($array as $key => $val) { /* ... */ } while(list($key, $val) = each($array)) { /* ... */ What should go in the missing line ????? below to produce the output shown? <?php$array_one = array(1,2,3,4,5);$array_two = array('A', 'B', 'C', 'D', 'E');??????? print_r($array_three);?> Result: Array( [5] => A [4] => B [3] => C [2] => D [1] => E) Answer... $array_three = array_merge(array_reverse($array_one), $array_two); $array_three = array_combine($array_one, $array_two); $array_three = array_combine(array_reverse($array_one), $array_two); $array_three = array_merge($array_one, $array_two); $array_three = array_reverse($array_one) + $array_two; Determining the User-Agent reported by the client making the PHP 5 request can be determined by doing what? Answer... Use the $_SERVER['USER_AGENT'] variable Use the $_SERVER['HTTP_USER_AGENT'] variable Using the function http_get_user_agent() Author : Jagat Kothari Page 33
    • None of the above When your error reporting level includes E_STRICT, what will the output of the following code be? <?phpfunction optionalParam($x = 1, $y = 5, $z){ if ((!$z > 0)) { $z = 1; } for($count = $x; $count < $y; $count+= $z) { echo "#"; }}optionalParam(2,4,2);?> Answer... ## Notice Warning Syntax Error # Which of the following aspects of the MVC pattern is used in conjunction with the database? Answer... Model Schema Validation Controller View The _____ keyword is used to block any overriding of a class/method by a subclass. Answer... static Author : Jagat Kothari Page 34
    • None of the above protected final private Consider the following script: <?php$dom = new DOMDOcument();$dom->load("myxmlfile.xml");foreach($dom- >documentElement->childNodes as $child){ if(($child->nodeType == XML_ELEMENT_NODE) && $child->nodeName == "item") { foreach($child->childNodes as $item) { if(($item->nodeType == XML_ELEMENT_NODE) && ($item->nodeName == "title")) { print "$item->firstChild- >datan"; } } }}?> Assuming the referenced XML document exists and matches the parsing logic, what should be displayed when this script is executed? Answer... None of the above The XML of each 'title' node The XML of each 'item' node "Title" for every title node in the document The contents of every 'title' node which exists under an 'item' node The _________ method can be used from a SimpleXML node to return an iterator containing a list of all of the current node's subnodes. children Author : Jagat Kothari Page 35
    • When writing portable database code using PDO, what is the PDO::ATTR_CASE attribute useful for? Answer... None of the above Ensuring that all columns are of a particular case when fetched Adjusting the case of a query before it is processed for compatibility reasons Controls the switch logic of how queries are processed Allows you to adjust the memory cache (or "case") for increased performance Which of the following are not true about streams? Answers: (choose 2) They are always seekable When used properly they significantly reduce memory consumption They can be applied to any data source They are always bi-directional They can be filtered Given the following PHP script: <?php $xmldata = <<< XML<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> <b>Hello, World!</b> </p> Author : Jagat Kothari Page 36
    • </body></html>XML;$sxe = simplexml_load_string($xmldata);$p = $sxe->body->p;$string = ???????? print $string;?> What should go in place of ????? above to print the string Hello, World! (with no leading/trailing whitespace or markup)? Answer... trim(($p[1])); trim(strip_tags(($p->asText()))); trim(strip_tags(($p->asXML()))); trim(($p->asXML())); strip_tags(($p->asXML())); Removing undesired markup tags from input can best be done using which function? strip_tags During an HTTP authentication, how does one determine the username and password provided by the browser? Answer... Parse the HTTP headers manually using http_get_headers() Use the get_http_username() and get_http_password() functions Use the $_SERVER['HTTP_USER'] and $_SERVER['HTTP_PASSWORD'] variables Use the $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] variables Parse the $_SERVER['REQUEST_URI'] variable Author : Jagat Kothari Page 37
    • Which of the following are not valid ways to embed a variable into a string? Answers: (choose 2) $a = "Value: $value->getValue()"; $a = "Value: {$value}"; $a = 'Value: $value'; $a = "Value: $value"; $a = "Value: {$value['val']}"; <?phpfunction get_socket($host, $port) { $fr = fsockopen($host, $port); stream_set_blocking($fr, false); return $fr;}// Assume $host1, $host2, etc are defined properly$write_map[] = array('fr' => get_socket($host1, $port1), 'data' => str_pad("", 500000, "A"));$write_map[] = array('fr' => get_socket($host2, $port2), 'data' => str_pad("", 500000, "B"));$write_map[] = array('fr' => get_socket($host3, $port3), 'data' => str_pad("", 500000, "C"));do { $write_sockets = array(); foreach($write_map as $data) { $write_sockets[] = $data['fr']; } $num_returned = stream_select($r = null, $write_sockets, $e = null, 30); if($num_returned) { foreach($write_sockets as $fr) { foreach($write_map as $index => $data) { if($data['fr'] === $fr) { $len = fwrite($fr, $data['buf']); if($len) { $data['buf'] = substr($data['buf'], $len); if(empty($data['buf'])) { fclose($data['fr']); /* ????????? */ } } } } } }} while(count($write_map));?> What should go in the ??????? above for this script to function properly? Which PCRE regular expression will match the string PhP5-rocks? Answer... /^[hp1-5]*-.*/i /[hp1-5]*-.?/ Author : Jagat Kothari Page 38
    • /[hp][1-5]*-.*/ /[PhP]{3}[1-5]{2,3}-.*$/ /[a-z1-5-]*/ What is the output of the following code? <?php$string = "111221";for($i = 0; $i < strlen($string); $i++) { $current = $string[$i]; $count = 1; while(isset($string[$i + $count]) && ($string[$i + $count] == $current)) $count++; $newstring .= "$count{$current}"; $i += $count-1;}print $newstring;?> What is wrong with the following code snippet? Assume default configuration values apply. <?php$fp = fsockopen('www.php.net', 80);fwrite($fp, "GET / HTTP/1.0rnHost: www.php.netrn"); $data = fread($fp, 8192);?> Answer... The request is blocking and may cause fread() to hang The HTTP request is malformed This script should be re-written using fgets() instead of fread() The request is non-blocking and fread() may miss the response You cannot use fwrite() with fsockopen() Author : Jagat Kothari Page 39
    • Consider the following code segment: <?php$xmldata = <<< XML<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> Moved to &lt;<a href="http://example.org/">http://www.example.org/</a>.&gt; <br/> </p> </body></html>XML;$xml = xml_parser_create("UTF-8");/* ??????? */xml_parse($xml, $xmldata);function xml_start_handler($xml, $tag, $attributes) {print "Tag: $tag<br/>n";}function xml_end_handler($xml, $tag) {}?> What should be placed in place of ?????? above to have the above script display the name of each tag within the XML document? Answer... xml_set_callback("xml_start_handler"); xml_set_element_handler($xml, "xml_start_handler", "xml_end_handler"); xml_node_set_handler("xml_start_handler", "xml_end_handler"); xml_node_set_handler("xml_start_handler"); ================================================================================== ================================ What is the output of the following code? <?php function functionSplit() { $pre = 1; Author : Jagat Kothari Page 40
    • ?> <?php echo $pre; } functionSplit(); ?> Answer... Error; function declarations can not be split over multiple PHP segments. Nothing 1 2 In a situation where you want one and only one instance of a particular object, the ________ design pattern should be used. Using flock() to lock a stream is only assured to work under what circumstances? Answer... When running in a Linux environment local filesystem When accessing the stream of the local filesystem When running in a Windows environment and accessing a share When accessing a bi-directional stream When accessing a read-only stream What is the best measure one can take to prevent a cross-site request forgery? Author : Jagat Kothari Page 41
    • Answer... Disallow requests from outside hosts Add a secret token to all form submissions Turn off allow_url_fopen in php.ini Filter all output Filter all input Determining the User-Agent reported by the client making the PHP 5 request can be determined by doing what? What is the output of the following code? <?php function x10(&$number) $number *= 10; $count = 5; x10($count); echo $count; ?> Answer... Error: Unexpected T_VARIABLE 10 Notice regarding pass by reference 50 5 Author : Jagat Kothari Page 42
    • What are the values of $a in $obj_one and $obj_two when this script is executed? <?php class myClass { private $a; public function __construct() { $this->a = 10; } public function printValue() { print "The Value is: {$this->a}n"; } public function changeValue($val, $obj = null) { if(is_null($obj)) { $this->a = $val; } else { $obj->a = $val; } } public function getValue() { return $this->a; Author : Jagat Kothari Page 43
    • } } $obj_one = new myClass(); $obj_two = new myClass(); $obj_one->changeValue(20, $obj_two); $obj_two->changeValue($obj_two->getValue(), $obj_one); $obj_two->printValue(); $obj_one->printValue(); ?> Answer... 10,20 You cannot modify private member variables of a different class 20,20 10,10 20,10 Consider the following code snippet: <?php $query = "INSERT INTO mytable (myinteger, mydouble, myblob, myvarchar) Author : Jagat Kothari Page 44
    • VALUES (?, ?, ?, ?)"; $statement = mysqli_prepare($link, $query); if(!$statement) { die(mysqli_error($link)); } /* The variables being bound to by MySQLi don't need to exist prior to binding */ mysqli_bind_param($statement, "idbs", $myinteger, $mydouble, $myblob, $myvarchar); /* ???????????? */ /* execute the query, using the variables as defined. */ if(!mysqli_execute($statement)) { die(mysqli_error($link)); } ?> Assuming this snippet is a smaller part of a correctly written script, what actions must occur in place of the ????? in the above code snippet to insert a row with the following values: 10, 20.2, foo, string ? Author : Jagat Kothari Page 45
    • When checking to see if two variables contain the same instance of an object, which of the following comparisons should be used? Answer... if($obj1->equals($obj2) && ($obj1 instanceof $obj2)) if($obj1->equals($obj2)) if($obj1 === $obj2) if($obj1 instanceof $obj2) if($obj1 == $obj2) Event-based XML parsing is an example of which parsing model? Answer... SAX DOM XML Object Mapping XPath XQuery Which two internal PHP interfaces provide functionality which allow you to treat an object like an array? Which string does the following PCRE regular expression match? Author : Jagat Kothari Page 46
    • $regex = "/^([a-z]{5})[1-5]+([a-z]+)/"; Answers: (choose 2) None of the above Hello34262343goodbye frank12345abc hello34212343goodbye abcdefghi12345abc Consider the following code: <?php header("Location: {$_GET['url']}"); ?> Which of the following values of $_GET['url'] would cause session fixation? The ____________ function is used to modify the amount of time PHP will wait for a stream before timing out during reading or writing. Given the following PHP script: <?php $xmldata = <<< XML Author : Jagat Kothari Page 47
    • <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> <b>Hello, World!</b> </p> </body> </html> XML; $sxe = simplexml_load_string($xmldata); $p = $sxe->body->p; $string = ???????? print $string; ?> What should go in place of ????? above to print the string Hello, World! (with no leading/trailing whitespace or markup)? Author : Jagat Kothari Page 48
    • Setting a HTTP cookie on the client which is not URL-encoded is done how in PHP 5? Answer... Use the setrawcookie() function Set the cookies.urlencode INI directive to false Use urldecode() on the return value of setcookie() Setting the $no_encode parameter of setcookie() to a boolean 'true' All cookies must be URL encoded ================================================================================== ===================================== Which key will not be displayed from the following code block? <?php $array = array('a' => 'John','b' => 'Coggeshall','c' => array('d' => 'John','e' => 'Smith')); function display($item, $key) { print "$key => $itemn"; } array_walk_recursive($array, "display"); ?> Author : Jagat Kothari Page 49
    • Answer... d c b a They all will be displayed Which of the following are not valid ways to embed a variable into a string? Answers: (choose 2) $a = "Value: $value->getValue()"; $a = "Value: {$value}"; $a = 'Value: $value'; $a = "Value: $value"; $a = "Value: {$value['val']}"; What is the best approach for converting this string: $string = "a=10&b[]=20&c=30&d=40+50"; Into this array? array(4) { ["a"]=> string(2) "10" ["b"]=> array(1) { [0]=> string(2) "20" } ["c"]=> string(2) "30" ["d"]=> string(5) "40 50"} Answer... Author : Jagat Kothari Page 50
    • Write a parser completely by hand, it's the only way to make sure it's 100% accurate Use the parse_str() function to translate it to an array() Pass the variable to another PHP script via an HTTP GET request and return the array as a serialized variable Just call unserialize() to translate it to an array() Write a string parser using strtok() and unserialize() to convert it to an array For an arbitrary string $mystring, which of the following checks will correctly determine if the string PHP exists within it? Answer... if(strpos($mystring, "PHP") !== false) if(!strpos($mystring,"PHP")) if(strpos($mystring, "PHP") === true) if(strloc($mystring, "PHP") == true) if(strloc($mystring, "PHP") === false) To destroy a PHP session completely, one must which of the following? Answers: (choose 2) Regenerate the session ID using session_regenerate_id() If cookies are used, destroy it Use session_demolish() to completely destroy the session Change the session name using session_name() Destroy the session data using session_destroy() What consistutes a View in the MVC pattern for PHP 5, in the following list? Author : Jagat Kothari Page 51
    • Answers: (choose 2) Iterators PDO Classes PHP Smarty Consider the following code: <?phpsession_start();if(!empty($_REQUEST['id']) && !empty($_REQUEST['quantity'])) { $id = scrub_id($_REQUEST['id']); $quantity = scrub_quantity($_REQUEST['quantity']) $_SESSION['cart'][] = array('id' => $id, 'quantity' => $quantity)}/* .... */?> What potential security hole would this code snippet produce? Answer... Cross-Site Scripting Attack There is no security hole in this code Code Injection SQL Injection Cross-Site Request Forgery Consider the following script: <?php $string = "<b>I like 'PHP' & I think it is "cool"</b>";var_dump(htmlentities($string, ENT_QUOTES));var_dump(print htmlspecialchars($string));?> In this script, do the two var_dump() calls produce the same string? Why or Why Not? Author : Jagat Kothari Page 52
    • Answer... No, the htmlentities() call will translate quotes while the htmlspecialchars() call will not No, htmlentites() translates < and > symbols to their HTML entity equivalents while htmlspecialchars() only does quotes No, the htmlentites() call won't translate quotes to HTML entities while the htmlspecialchars() call will Yes, htmlspecialchars() and htmlentities() with the ENT_QUOTES constants produce the same result Consider the following code: <?phpheader("Location: {$_GET['url']}");?> Which of the following values of $_GET['url'] would cause session fixation? Answers: (choose 1) Session Fixation is not possible with this code snippet http://www.zend.com/?PHPSESSID=123 PHPSESSID%611243 Set-Cookie%3A+PHPSESSID%611234 http%3A%2F%2Fwww.zend.com%2F%0D%0ASet-Cookie%3A+PHPSESSID%611234 Implementing your own PDO class requires which steps from the list below? Answers: (choose 3) Extending the PDOStatement Class Author : Jagat Kothari Page 53
    • Set the PDO::ATTR_STATEMENT_CLASS parameter Call the PDO::setStatementClass() method Extend the PDO class Set the PDO::ATTR_USE_CLASS paramater <?php $a = 010;$b = 0xA;$c = 2;print $a + $b + $c; ?> Answer... 20 22 18 $a is an invalid value 2 <?php class myClass { private $a; public function __construct() { $this->a = 10; } public function printValue() { print "The Value is: {$this->a}n"; } public function changeValue($val, $obj = null) { if(is_null($obj)) { $this->a = $val; } else { $obj->a = $val; } } public function getValue() { return $this->a; }}$obj_one = new myClass();$obj_two = new myClass();$obj_one- >changeValue(20, $obj_two);$obj_two->changeValue($obj_two->getValue(), $obj_one);$obj_two- >printValue();$obj_one->printValue();?> Answer... 10,20 You cannot modify private member variables of a different class 20,20 10,10 Author : Jagat Kothari Page 54
    • 20,10 Which of the following SQL statements will improve SQLite write performance? Answers: (choose 2) PRAGMA locking_mode = "Row"; PRAGMA count_changes = Off; PRAGMA default_synchronous = Off; PRAGMA default_synchronous = On; PRAGMA locking_mode = "Table"; ================================================================================== ================================= Assuming every method call below returns an instance of an object, how can the following be re- written in PHP 5? <?php$a = new MyClass();$b = $a->getInstance();$c = $b->doSomething();?> Answer... $c = ((MyClass)$a->getInstance())->doSomething(); This cannot be re-written in PHP 5 $c = $a->getInstance()->doSomething(); $c = (MyClass)$a->getInstance(); $c = (new MyClass())->getInstance()->doSomething(); Author : Jagat Kothari Page 55
    • The following PHP script is an example of which design pattern? <?phpinterface HashAlgorithm { public function hash($value); }class MyClass { private $value; public function __construct($value) { $this->value = $value; } public function hash(HashAlgorithm $a) { return $a->hash($this->value); }}class MD5Hash implements HashAlgorithm { public function hash($value) { return md5($hash); }}$obj = new MyClass("John"); $obj->hash(new MD5Hash());?> Answer... Controller Strategy Abstract Factory Factory Command Chain Consider the following PHP script: <?phpfunction get_socket($host, $port) { $fr = fsockopen($host, $port); stream_set_blocking($fr, false); return $fr;}// Assume $host1, $host2, etc are defined properly$write_map[] = array('fr' => get_socket($host1, $port1), 'data' => str_pad("", 500000, "A"));$write_map[] = array('fr' => get_socket($host2, $port2), 'data' => str_pad("", 500000, "B"));$write_map[] = array('fr' => get_socket($host3, $port3), 'data' => str_pad("", 500000, "C")); do { $write_sockets = array(); foreach($write_map as $data) { $write_sockets[] = $data['fr']; } $num_returned = stream_select($r = null, $write_sockets, $e = null, 30); if($num_returned) { foreach($write_sockets as $fr) { foreach($write_map as $index => $data) { if($data['fr'] === $fr) { $len = fwrite($fr, $data['buf']); if($len) { $data['buf'] = substr($data['buf'], $len); if(empty($data['buf'])) { fclose($data['fr']); unset($write_map[$index]); } } } } } }} while(??????????);?> What should go in the ??????? above for this script to function properly? Author : Jagat Kothari Page 56
    • Answer... $num_returned > 0 $len > 0 !empty($data['buf']) count($write_sockets) count($write_map) When your error reporting level includes E_STRICT, what will the output of the following code be? <?phpfunction optionalParam($x = 1, $y = 5, $z){ if ((!$z > 0)) { $z = 1; } for($count = $x; $count < $y; $count+= $z) { echo "#"; }}optionalParam(2,4,2);?> Answer... ## Notice Warning Syntax Error # Consider the following code: <?phpsession_start();if(!empty($_REQUEST['id']) && !empty($_REQUEST['quantity'])) { $id = scrub_id($_REQUEST['id']); $quantity = scrub_quantity($_REQUEST['quantity']) $_SESSION['cart'][] = array('id' => $id, 'quantity' => $quantity)}/* .... */?> What potential security hole would this code snippet produce? Answer... Author : Jagat Kothari Page 57
    • Cross-Site Scripting Attack There is no security hole in this code Code Injection SQL Injection Cross-Site Request Forgery Consider the following code: <?phpheader("Location: {$_GET['url']}");?> Which of the following values of $_GET['url'] would cause session fixation? Answers: (choose 1) Session Fixation is not possible with this code snippet http://www.zend.com/?PHPSESSID=123 PHPSESSID%611243 Set-Cookie%3A+PHPSESSID%611234 http%3A%2F%2Fwww.zend.com%2F%0D%0ASet-Cookie%3A+PHPSESSID%611234 To ensure that a given object has a particular set of methods, you must provide a method list in the form of an ________ and then attach it as part of your class using the ________ keyword. Answer... array, interface interface, implements interface, extends instance, implements Author : Jagat Kothari Page 58
    • access-list, instance <?phptry { $dbh = new PDO("sqlite::memory:");} catch(PDOException $e) { print $e->getMessage();} $dbh->query("CREATE TABLE foo(id INT)");$stmt = $dbh->prepare("INSERT INTO foo VALUES(:value)");$value = null;$data = array(1,2,3,4,5);$stmt->bindParam(":value", $value);/* ?????? */try { foreach($data as $value) { /* ????? */ }} catch(PDOException $e) { /* ??????? */}/* ?????? */?> Answers: (choose 4) $dbh->beginTransaction(); $dbh->commit(); $stmt->execute(); $dbh->rollback(); $dbh->query($stmt); The _______ constant in a CLI script is an automatically provided file resource representing standard input of the terminal. Answer... STDIN __STDIN__ STDIO PHP::STDIO STD_IN In databases that do not support the AUTO_INCREMENT modifier, you must use a _________ instead to auto-generate a numeric incrementing key PHP 5 supports which of the following XML parsing methods? Author : Jagat Kothari Page 59
    • Answers: (choose 4) SAX FastDOM DOM XPath XML to Object mapping Given the string: $var = "john@php.net"; Which of the following will extract the TLD (top level domain) of ".net" from the string? Answer... strstr($var, strpos($var, ".")); substr($var, strpos($var, "@")); substr($var, strstr($var, ".")); substr($var, strpos($var, ".") + 1); substr($var, strpos($var, ".")); <?php$a = 1;$b = 2.5;$c = 0xFF;$d = $b + $c;$e = $d * $b;$f = ($d + $e) % $a;print ($f + $e);?> Answer... Author : Jagat Kothari Page 60
    • 643.75 432 643 257 432.75 <?php$title = $dom->createElement('title');$node = ????????$title->appendChild($node);$head- >appendChild($title);?> What should ??????? be replaced with to add a <title> node with the value of Hello, World! Answer... $dom->createTextNode("Hello, World"); $dom->appendElement($title, "text", "Hello, world!"); $dom->appendTextNode($title, "Hello, World!"); $dom->createElement('text', "Hello, World"); None of the above The _________ context variable allows you to define a callback for the stream that will notify your script of certain events during the course of the transaction. What is the output of the following code? Author : Jagat Kothari Page 61
    • <?phpclass MyException extends Exception {}class AnotherException extends MyException {}class Foo { public function something() { throw new AnotherException(); } public function somethingElse() { throw new MyException(); }}$a = new Foo();try { try { $a->something(); } catch(AnotherException $e) { $a->somethingElse(); } catch(MyException $e) { print "Caught Exception"; }} catch(Exception $e) { print "Didn't catch the Exception!";}?> Answer... "Caught Exception" followed by "Didn't catch the Exception!" A fatal error for an uncaught exception "Didn't catch the Exception!" "Didn't catch the Exception!" followed by a fatal error "Caught Exception" <?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> Moved to <<a href="http://example.org/">http://www.example.org/</a>.> <br> </p> </body></html> What is wrong with this document, and how can it be corrected? Answers: (choose 2) The document is completely valid All special XML characters must be represented as entities within the content of a node All tags must be closed You cannot specify a namespace for the <html> attribute The DOCTYPE declaration is malformed What combination of boolean values for $a, $b, $c, and $d will result in the variable $number being equal to 3? Author : Jagat Kothari Page 62
    • <?php$a = null;$b = null;$c = null;$d = null;if($a && !$b) { if(!!$c && !$d) { if($d && ($a || $c)) { if(!$d && $b) { $number = 1; } else { $number = 2; } } else { $number = 3; } } else { $number = 4; }} else { $number = 5;}?> Answer... false, true, true, true true, false, true, false true, true, false, false false, true, true, false false, false, true, false function oranges(&$oranges = 17){ $oranges .= 1;}$apples = 5;oranges($apples);echo $apples++; Answer... 16 51 15 6 5 ================================================================================== ================== One can ensure that headers can always be sent from a PHP script by doing what? Answer... Enable header buffering in PHP 5 Author : Jagat Kothari Page 63
    • Set the header.force INI directive to true Enable output buffering in PHP 5 There is no way to ensure that headers can always be set, they must always be checked None of the above When connecting to a database using PDO, what must be done to ensure that database credentials are not compromised if the connection were to fail? Answer... wrap the PDO DSN in a try/catch block to catch any connection exception Use constants in the PDO DSN Place the login credentials in the php.ini file Disable E_STRICT and E_NOTICE error reporting levels Consider the following script: <?php$string = "<b>I like 'PHP' & I think it is "cool"</b>";var_dump(htmlentities($string, ENT_QUOTES));var_dump(print htmlspecialchars($string));?> In this script, do the two var_dump() calls produce the same string? Why or Why Not? Answer... No, the htmlentities() call will translate quotes while the htmlspecialchars() call will not No, htmlentites() translates < and > symbols to their HTML entity equivalents while htmlspecialchars() only does quotes No, the htmlentites() call won't translate quotes to HTML entities while the htmlspecialchars() call will Yes, htmlspecialchars() and htmlentities() with the ENT_QUOTES constants produce the same result Author : Jagat Kothari Page 64
    • Given the following XML document in a SimpleXML object: <?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</ title> </head> <body> <p> Moved to &lt;<a href="http://example.org/">http://www.example.org/</a>.&gt; <br/> </p> </body></html> Select the proper statement below which will display the HREF attribute of the anchor tag. Answer... $sxe->body->p[0]->a[1]['href'] $sxe->body->p->a->href $sxe->body->p->a['href'] $sxe['body']['p'][0]['a']['href'] $sxe->body->p[1]->a['href'] Consider the following simple PHP script: <?php$dom = new DomDocument();$dom->load('test.xml');$xpath = new DomXPath($dom);$nodes = $xpath->query(???????, $dom->documentElement);echo $nodes->item(0)- >getAttributeNode('bgcolor')->value . "n";?> What XPath query should go in the ?????? above to display the "bgcolor" attribute of the first "body" node in the XML document? Answer... "*[local-name()='body']" Author : Jagat Kothari Page 65
    • "/body[0]/text" "/body/body[0]" "name='body'" "*[lname()='body']" What is the output of the following code? <?php$string = "111221";for($i = 0; $i < strlen($string); $i++) { $current = $string[$i]; $count = 1; while(isset($string[$i + $count]) && ($string[$i + $count] == $current)) $count++; $newstring .= "$count{$current}"; $i += $count-1;}print $newstring;?> Answer... 312211 3312212 11221221 221131 3211122 What is the output of the following code block? <?php$a = "The quick brown fox jumped over the lazy dog.";$b = array_map("strtoupper", explode(" ", $a));foreach($b as $value) { print "$value ";}?> Answer... Author : Jagat Kothari Page 66
    • THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG. A PHP Error The quick brown fox jumped over the lazy dog. Array Array Array Array Array Array Array Array Array the quick brown fox jumped over the lazy dog. What is the output of the following code? <?phpfunction x10(&$number) $number *= 10;$count = 5;x10($count);echo $count;?> Answer... Error: Unexpected T_VARIABLE 10 Notice regarding pass by reference 50 5 Which of the following is not valid syntax for creating a new array key? Answer... $a[] = "value"; $a{} = "value"; $a[0] = "value"; $a{0} = "value"; Author : Jagat Kothari Page 67
    • $a[$b = 0] = "value"; <?php$fp = fsockopen('www.php.net', 80);fwrite($fp, "GET / HTTP/1.0rnHost: www.php.netrn"); $data = fread($fp, 8192);?> Answer... The request is blocking and may cause fread() to hang The HTTP request is malformed This script should be re-written using fgets() instead of fread() The request is non-blocking and fread() may miss the response You cannot use fwrite() with fsockopen() What is the output of the following? <?php function byRef(&$number){ $number *= 10; return ($number - 5);}$number = 10;$number = byRef($number);echo $number;?> Answer... 50 5 95 10 100 Which of the following functions is used to determine if a given stream is blocking or not? Author : Jagat Kothari Page 68
    • Answer... stream_get_blocking stream_get_meta_data stream_is_blocking stream_get_blocking_mode When working with SimpleXML in PHP 5, the four basic rules on how the XML document is accessed are which of the following? Answers: (choose 4) Element namespaces are denoted by the 'namespace' attribute converting an element to a string denotes text data Non-numeric indexes are element attributes Numeric indexes are elements Properties denote element iterators What is wrong with the following code valid in PHP 4 but invalid in PHP 5? <?php class MyClass { function reassign($var) { $this = $var; }}$a = new MyClass();$b = new MyClass();$a->reassign($b); ?> Answer... Reassigning $this in PHP 5 throws a fatal error It is missing access restrictions (public,private,protected) required in PHP 5 Classes need to implement the OverLoad interface for this behavior in PHP 5 Author : Jagat Kothari Page 69
    • $b is now an object handle and the reassign() method needs to be declared pass-by-reference What is the output of the following code? <?php function byReference(&$variable = 5){ echo ++$variable;}byReference();?> Answer... No output or error. Variables can not be optional and passed by reference. 5 6 When your error reporting level includes E_STRICT, what will the output of the following code be? <?phpfunction optionalParam($x = 1, $y = 5, $z){ if ((!$z > 0)) { $z = 1; } for($count = $x; $count < $y; $count+= $z) { echo "#"; }}optionalParam(2,4,2);?> Answer... ## Notice Warning Syntax Error # Which of the following is not a valid PDO DSN? Answer... Author : Jagat Kothari Page 70
    • All of the above are valid mysql:unix_socket=/tmp/mysql.sock;dbname=testdb oci:dbname=//localhost:1521/mydb mysql:host=localhost;port=3307;dbname=testdb sqlite2:/opt/databases/mydb.sq2 What XML technology is used when you mix two different document types in a single XML document? Answer... Validators DTD Transformations Namespaces ================================================================================== ================== The _________ context variable allows you to define a callback for the stream that will notify your script of certain events during the course of the transaction. Given the following XML document in a SimpleXML object: Author : Jagat Kothari Page 71
    • <?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</ title> </head> <body> <p> Moved to &lt;<a href="http://example.org/">http://www.example.org/</a>.&gt; <br/> </p> </body></html> Select the proper statement below which will display the HREF attribute of the anchor tag. Answer... $sxe->body->p[0]->a[1]['href'] $sxe->body->p->a->href $sxe->body->p->a['href'] $sxe['body']['p'][0]['a']['href'] $sxe->body->p[1]->a['href'] <?phpfunction byRef(&$apples){ $apples++;}$oranges = 5;$apples = 5;byRef($oranges);echo "I have $apples apples and $oranges oranges";?> Answer... I have 6 apples and 6 oranges I have 6 apples and 5 oranges I have 5 apples and 6 oranges I have 5 apples and 5 oranges Which of the following is the best way to split a string on the "-=-" pattern? Answer... Author : Jagat Kothari Page 72
    • They all are equally proper methods str_split($string, strpos($string, "-=-")) preg_split("-=-", $string); explode("-=-" $string); ================================================================================== ================== The _________ context variable allows you to define a callback for the stream that will notify your script of certain events during the course of the transaction. <?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>XML Example</title> </head> <body> <p> Moved to &lt;<a href="http://example.org/">http://www.example.org/</a>.&gt; <br/> </p> Author : Jagat Kothari Page 73
    • </body> </html> Answer... $sxe->body->p[0]->a[1]['href'] $sxe->body->p->a->href $sxe->body->p->a['href'] $sxe['body']['p'][0]['a']['href'] $sxe->body->p[1]->a['href'] Answers: (choose 3) 't' == t 1 === "1time" "top" == 0 "top" === 0 1 == "1time" <?php $fp = fsockopen('www.php.net', 80); fwrite($fp, "GET / HTTP/1.0rnHost: www.php.netrn"); $data = fread($fp, 8192); Author : Jagat Kothari Page 74
    • ?> Answer... The request is blocking and may cause fread() to hang The HTTP request is malformed This script should be re-written using fgets() instead of fread() The request is non-blocking and fread() may miss the response You cannot use fwrite() with fsockopen() The ________ method in the PDOStatement class is used to return the next result set in a multi- query statement. <?php function a($number) { return (b($number) * $number); } function b(&$number) { ++$number; } echo a(5); ?> Author : Jagat Kothari Page 75
    • Answer... 0 36 6 30 5 When connecting to a database using PDO, what must be done to ensure that database credentials are not compromised if the connection were to fail? Answer... wrap the PDO DSN in a try/catch block to catch any connection exception Use constants in the PDO DSN Place the login credentials in the php.ini file Disable E_STRICT and E_NOTICE error reporting levels <?php $array = array('a' => 'John', 'b' => 'Coggeshall', 'c' => array('d' => 'John', Author : Jagat Kothari Page 76
    • 'e' => 'Smith')); function something($array) { extract($array); return $c['e']; } print something($array); ?> When opening a file in writing mode using the FTP handler, what must be done so that the file will still be written to the server in the event it previously exists? Answer... Provide a context for fopen() using stream_context_create() You must delete the file first before uploading a new file Configure this behavior in the php.ini file using the ftp.overwrite directive Open the file using the 'w+' mode Which of the following is not a valid default stream wrapper for PHP 5, assuming OpenSSL is enabled? Answer... Author : Jagat Kothari Page 77
    • ftps:// ftp:// sftp:// https:// http:// <?php $a = 1; $b = 2.5; $c = 0xFF; $d = $b + $c; $e = $d * $b; $f = ($d + $e) % $a; print ($f + $e); ?> Answer... 643.75 432 643 257 432.75 Author : Jagat Kothari Page 78
    • The method used to create a new node to be added into an XML document using DOM is the ___________ method <?php function 1dotEach($n) { if ($n > 0) { 1dotEach(--$n); echo "."; }else { return $n; } } 1dotEach(4); ?> Answer... ...0 Parse Error: Syntax Error ..... .... Author : Jagat Kothari Page 79
    • ... <?php class MyException extends Exception {} class AnotherException extends MyException {} class Foo { public function something() { throw new AnotherException(); } public function somethingElse() { throw new MyException(); } } $a = new Foo(); try { try { $a->something(); } catch(AnotherException $e) { $a->somethingElse(); } catch(MyException $e) { print "Caught Exception"; Author : Jagat Kothari Page 80
    • } } catch(Exception $e) { print "Didn't catch the Exception!"; } ?> Answer... "Caught Exception" followed by "Didn't catch the Exception!" A fatal error for an uncaught exception "Didn't catch the Exception!" "Didn't catch the Exception!" followed by a fatal error "Caught Exception" <?php class myClass { private $a; public function __construct() { $this->a = 10; } Author : Jagat Kothari Page 81
    • public function printValue() { print "The Value is: {$this->a}n"; } public function changeValue($val, $obj = null) { if(is_null($obj)) { $this->a = $val; } else { $obj->a = $val; } } public function getValue() { return $this->a; } } $obj_one = new myClass(); $obj_two = new myClass(); $obj_one->changeValue(20, $obj_two); $obj_two->changeValue($obj_two->getValue(), $obj_one); $obj_two->printValue(); $obj_one->printValue(); ?> Author : Jagat Kothari Page 82
    • Answers: (choose 2) $a = "Value: $value->getValue()"; $a = "Value: {$value}"; $a = 'Value: $value'; $a = "Value: $value"; $a = "Value: {$value['val']}"; Which of the following functions were added to PHP 5 for dealing with arrays? Answers: (choose 2) array_intersect_key() array_unshift() array_diff_key() array_merge() array_slice() <?php function byRef(&$apples) { $apples++; } Author : Jagat Kothari Page 83
    • $oranges = 5; $apples = 5; byRef($oranges); echo "I have $apples apples and $oranges oranges"; ?> ================================================================================== ================== function oranges(&$oranges = 17) { $oranges .= 1; } $apples = 5; oranges($apples); echo $apples++; What does the following function do, when passed two integer values for $p and $q? <?php function magic($p, $q) { return ($q == 0) ? $p Author : Jagat Kothari Page 84
    • : magic($q, $p % $q); } ?> Answer... Loops infinitely Switches the values of $p and $q Determines if they are both even or odd Determines the greatest common divisor between them Calculates the modulus between the two <?php $array = array(1 => 0, 2, 3, 4); array_splice($array, 3, count($array), array_merge(array('x'), array_slice($array, 3))); print_r($array); ?> Author : Jagat Kothari Page 85