Zend PHP5 Certification Presented by – Rakesh Kumar, Rajul Gupta, and Ankur Aeran OSSCube
Who we are? • Rakesh Kumar – Senior project manager – PHP and related frameworks/Products, Senior consultant and trainer – MySQL, Started as PHP Developer • Rajul Gupta – Senior consultant – CRM – PHP evangelist and ZCE • Ankur Aeran – Tech Lead – Drupal – ZCE, First Zend Framework Certified (India) Zend PHP5 Certification, OSIdays 2010 Chennai
Why certification? • Industry-wide standard and a measure of distinction • Certification is recognition of a set of capabilities that the person taking the test has developed • ZCE certification helps other people (e.g., potential • employers) answer questions like: – “How predictably is the person likely to perform when applying PHP 5 technology to a business problem?” – “Has this applicant reached a pre-defined minimum standard of experience to undertake professional quality work?” Zend PHP5 Certification, OSIdays 2010 Chennai
Preparation tools • Instructor lead Online training – Register via website http://www.zend.com/ – Includes certification voucher • Instructor lead classroom training – Authorized training partners • Zend PHP5 Certification Study Guide • Zend PHP5 Certification online practice exam • http://www.zend.com/en/services/certification/php-5-ce Zend PHP5 Certification, OSIdays 2010 Chennai
About the exam • Composed of ~70 randomly generated questions • Allowed 90 minutes to answer the questions • Questions cover twelve different topic areas • Questions vary in their degree of difficulty • Encompasses curriculum specified by the Zend PHP Education Advisory Board – Completely neutral – Exam excludes references or questions related to Zend‘s products Zend PHP5 Certification, OSIdays 2010 Chennai
Taking the exam • Exam administered at a Pearson VUE training center ( http://www.pearsonvue.com/) • Register for the exam via telephone or email – May differ by country; please check online • Bring two IDs, one must have your photo (and both must have your signature) • You will receive “scratch“ paper or an eraseable board for calculations at the time you take the test • You are not permitted to bring any materials into the room with you Zend PHP5 Certification, OSIdays 2010 Chennai
Questions & Strategies • There are several different types of questions, which we will discuss: • Multiple choice, only one answer is correct – Try to eliminate wrong answers – It makes no difference whether you incorrectly answer a question, or do not answer it at all, so... – Guess! Zend PHP5 Certification, OSIdays 2010 Chennai
Questions & Strategies • Multiple choice, several answers may be correct – Most of the time you are told the number of answers to select – Based on the number of correct answers, you may be able to eliminate some choices Zend PHP5 Certification, OSIdays 2010 Chennai
Questions & Strategies Freetext • Most of the time, questions are of this type: – What is the output of the following code? – What is the name of the function/setting/constant/… that does X-Y-Z? • Be careful when entering the answer! – No whitespace, explanations, comments, ... – Use lowercase letters with functions Zend PHP5 Certification, OSIdays 2010 Chennai
Testing software • You can mark questions for review – Be sure to check whether there are any questions marked for review before you submit your test • You can mark questions for comment – If there is something you would like the committee to know about a particular question, please use the Comment option to communicate back with Zend • You can easily navigate back to questions you have marked, but not the others, so remember this feature Zend PHP5 Certification, OSIdays 2010 Chennai
At the end • You’ll immediately get your test result from the testing center; usually printed out – Passed/Failed • No detailed score – If you fail, you will receive feedback about how you did in each topic area (weak -> strong) Zend PHP5 Certification, OSIdays 2010 Chennai
Basic exam information • You do not have to code large portions for the exam • You do have to answer freetext questions which may contain variable names, small snippets of code, etc. • You do NOT have to memorize the PHP manual – Technically, there are some places where you do, such as remembering which order the parameters for a given function are • You must analyze PHP code • You must know important PHP functions Zend PHP5 Certification, OSIdays 2010 Chennai
System information • The certification is independent of the operating system and a specific database • A general understanding of related technologies like HTTP or SQL is required • Questions refer to a virtual PHP system with the recommended configuration: – register_globals is Off, magic quotes are off, error reporting is set to E_ALL – errors are displayed (unless otherwise noted) Zend PHP5 Certification, OSIdays 2010 Chennai
About this session • We will give overview of all 12 topic areas • Major session focus is on some complex questions and how to deal with them • Obviously there is not enough time to cover every detail • But there is enough time to give bird’s eye view and briefly describe what is required for passing the exam Zend PHP5 Certification, OSIdays 2010 Chennai
The topic areas • PHP Basics • Web Features • Functions • PHP 4/5 Differences • Arrays • Files, Streams, Network • OOP • XML and Web Services • Strings and Regular • Database Expressions • Security • Design and Theory Zend PHP5 Certification, OSIdays 2010 Chennai
Embedding PHP There are several options to embed PHP code in an HTML document <?php <? <% <script language="php"> <?= Do all of these work well in any of the environments? Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output for the following code? <?php $a=10; ?> <?php=$a?> a)Fatal error b)Parser error c)Warning d)Notice e)10 Zend PHP5 Certification, OSIdays 2010 Chennai
Basic PHP Elements Variable (case-sensitive) ${‘foo’} Variable Variables $bar = “My Value”; $foo = “bar”; $$foo; Constants define('myPHPVER2', 5.1.0, true); //case insensitive Can we undefine a contstant? Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? echo strlen(‘anb’) * strlen(“anb”); Is the following statement correct? ${"function(){ this is a truely awful name for a variable }"} Is there any difference between echo() and print()? Zend PHP5 Certification, OSIdays 2010 Chennai
Bitwise Operators Left shift: << o Multiply by 2, x times (x is the operand after <<) o 3 << 4 == 48 (3 * 2^4 = 3 * 16) Right shift: >> o Divide by 2, x times (x is the operand after <<) o 4 >> 2 == 1 (4 / 2^2 = 4 / 4) • Negate bits: ~ Turns 0s into 1s, 1s into 0s Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php $a = 12; Echo ++$a + $a++ +$a; ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz class test{ public function abc() { global $x; $x = 15; echo "In ABC -".$x; } public function pqr() { echo " In PQR -".$x; //Notice x is undefined. } } $testObj = new test(); $testObj->abc(); $testObj->pqr(); echo " Out ".$x;*/ Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz class test{ global $x; public function abc() { $this->x = 15; echo "In ABC -".$this->x; } public function pqr() { echo " In PQR -".$this->x; } } $testObj = new test(); $testObj->abc(); $testObj->pqr(); echo " Out ".$x;*/ Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php $a = 6; echo ($a % 2) ? ($a%3) : ($a % 4); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Declare Functions With (optional) parameters and (optional) return value function myFunction($p) { // do something return $p; } $x = myFunction("ABC"); //$x == "ABC" $x = myFunction(); //warning! If warning then what is the solution? Zend PHP5 Certification, OSIdays 2010 Chennai
Function Parameters Accessing parameters func_num_args(): Number of parameters func_get_arg(nr): Parameter number nr func_get_args(): All parameters as an array function addValues() { $sum = 0; for ($i = 0; $i < func_num_args(); $i++) { $sum += func_get_arg($i); } return $sum; } Zend PHP5 Certification, OSIdays 2010 Chennai
Variable functions Variable functions work just like variable variables function xyz() { echo "XYZ"; } $d = "abc"; $abc = "xyz"; $$d(); // $$d() == ${"abc"}() == $abc() == xyz() Zend PHP5 Certification, OSIdays 2010 Chennai
Arrays Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php $a = array(“1” => 10, 1=> ‘B’, “C”, 2=>’D’); echo count($a); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php $a = array(); For ($i = 0; $i < 20; $i++) { $a[$i/10] = $i; } echo count($a); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php echo count ( range( 5.0, 3.0, 0.25)); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Built-in function • Remember names and arguments – Commonly used array function (e.g. array_shift, in_array,is_array) – Checking for value functions – Sorting functions Zend PHP5 Certification, OSIdays 2010 Chennai
OOP • Class declaration • Inheritance • Interface • Abstract classes • Autoloading • Magic methods • Cloning Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz Which of these may be declared as final? 1.Class 2.Method, 3.Variable Zend PHP5 Certification, OSIdays 2010 Chennai
Converting Objects Into Strings - Quiz class myClass { function __toString() { echo 'ABC'; } } $c = new myClass(); echo $c; // ABC • Only works when directly called using echo/print Zend PHP5 Certification, OSIdays 2010 Chennai
Autoloading If a non-existing class is instantiated, PHP executes the __autoload() function, if available Parameter: Name of the missing class function __autoload($c) { include_once "./classes/class_$c.php"; } $c = new myClass(); //loads ./classes/class_myClass.php Zend PHP5 Certification, OSIdays 2010 Chennai
Copying Objects • Objects are always passed by reference • Cloning an object causes the object itself to be copied instead of passing the reference • Keyword clone $c1 = new myClass(); $c2 = clone $c1; • PHP executes the special method __clone() upon cloning (if available) Zend PHP5 Certification, OSIdays 2010 Chennai
Serializing Objects • Serializing objects and arrays with serialize() $s = serialize(array(1, 2, 3)); // $s == 'a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}‘ • De-serializing strings with unserialize() $a = unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // $a == array(1, 2, 3) • Upon serialization, the special method __sleep() is executed (if available) • Upon de-serialization, the special method __wakeup() is executed (if available) Zend PHP5 Certification, OSIdays 2010 Chennai
STRING Zend PHP5 Certification, OSIdays 2010 Chennai
Looking For Strings The strpos() function returns the position of the first occurrence – or false. strpos(haystack, needle) strpos(haystack, needle, starting offset) Pay attention to the data type of the return value! 0 means that there was a match at position zero False means no match was made Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz What is the output of the following code? <?php $url = ‘http://myDomain.com/script.php’; $pattern = ‘http://’ If (strpos($url, $pattern)) { echo ‘URL Found’; } Else { echo ‘URL not found’; } ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Substrings substr(string, start, length) Returns a substring Negative start value: Counting starts at the end of the string What is the output of the following code? <?php Echo substr(‘123456’,-4,-2); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Comparing Strings • Operator ==: Comparison including data type conversion • Operator ===: Comparison including data type check • strcmp(): Case-sensitive comparison • strcasecmp(): Case-insensitive comparison • Return value of str*cmp(): 0 if equal Not 0 if inequal ($a == $b) * strcmp($a, $a) is equal to ??? Zend PHP5 Certification, OSIdays 2010 Chennai
Counting Strings • Number of characters strlen(string) Do not confuse with count() (array function)! • Number of words str_word_count(string) str_word_count(strings, true) yields array with all single words Zend PHP5 Certification, OSIdays 2010 Chennai
Strings And Arrays • explode(split string, string) Converts a string into an array • implode(glue string, string) Converts an array into a string What is the return value of the following code? <?php Echo count(implode(‘.’,’3 … 2 … 1 … still thinking!’); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
Formatted Output • printf(): Prints a formatted string • sprintf(): Returns a formatted string • vprintf(): Prints a formatted string, placeholder values supplied as an array • vsprintf():Returns a formatted string, placeholder values supplied as an array • fprintf(): Sends a formatted string to a resource Zend PHP5 Certification, OSIdays 2010 Chennai
Regular Expressions • A regular expression describes a pattern • Looking for patterns is more powerful than looking for (static) strings, though it comes at a cost to performance • Boundaries ^ (start of a line, though not necessarily start of the string) $ (end of a line , though not necessarily end of the string) A (start of the string) Z (end of the string) b (start or end of a word) B (not start or end of a word) Zend PHP5 Certification, OSIdays 2010 Chennai
Built-in character classes d (digit) D (no digit) s (whitespace) S (no whitespace) w (letter, digit, underscore) W (no letter or digit or underscore) . (any character) Zend PHP5 Certification, OSIdays 2010 Chennai
Quantifier * (any number of times) + (any number of times, at least once) ? (0 or 1) {n} (n times) {n,} (at least n times) {,m} (at max m times) {n,m} (at least n times, at max m times) Zend PHP5 Certification, OSIdays 2010 Chennai
Pattern matching • preg_match(pattern, string) • Return value: Number of matches But: Search ends after the first match Therefore return value 0 or 1 • Match details: third parameter preg_match($pattern, $string, &$matches) o $matches[0]: Complete match o $matches[1]: First submatch and so on Zend PHP5 Certification, OSIdays 2010 Chennai
Preg Functions preg_match_all($pattern, $string, $matches): Returns all matches preg_replace(search pattern, replace pattern,string) Zend PHP5 Certification, OSIdays 2010 Chennai
Design and Theory Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 1 Problem: Object access to a (relational) database Solution: Active Record • ORM: Object-Relational Mapping Use objects during development The system in the background takes care of the communication with the database Typically, a row in the database would be mapped to an Object Example in the PHP world: Doctrine, Propel Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 2 • Problem: Create complex objects in a simple way • Solution: Factory • Old code: $db = new MySQLiConnection(); //several times • Hard to migrate to another DBMS! New code: • static function factoryDB() { return new DBConnection('MySQLi'); } • factoryDB() is the factory Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 3 • Problem: Architectural model for web applications • Solution: MVC • Model Encapsulates business logic and application data • View Outputs model data • Controller Controls the application flow Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 4 • Problem: Indirect access to an object • Solution: Proxy • Used with many web services implementations $s = new SOAPClient('http://example.com/xy.wsdl'); $s->method(); • The local object behaves like the remote object • The background implementation takes care of communication, etc. Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 5 • Problem: Only one instance of an object shall be used at any time • Solution: Singleton class SingletonPattern { static $conn = null; static function getConnection() { if ($conn == null) { SingletonPattern::$conn = factoryDB('MySQLi'); } return SingletonPattern::$conn; } Zend PHP5 Certification, OSIdays 2010 } Chennai
Web Features • Where is form data put with a GET HTTP request? * Where is form data put with a POST HTTP request? • In the following list, the elements "one" and "three" get selected. • • When submitting the form, which values will be found in $_GET or $_POST? Zend PHP5 Certification, OSIdays 2010 Chennai
File Uploads •* HTML element: <input type="file" /> •* Required attribute in the <form> element: enctype="multipart/form-data" •* $_FILES ( Array keys are name, type, size, tmp_name, error) •* Uploads will be deleted after script execution  Copy away using copy_uploaded_file()  Move away using move_uploaded_file()  Check using is_uploaded_file()
Quiz • When opening a file in writing mode using FTP handler, what must be done so that file will still be written to the server in the event it previously exists? – Provide contest for fopen() using stream_context_create() – You must delete the file first before uploading a new file – Configure this behavior in php.ini using ftp.overwrite directive – Open the file using w+ mode Zend PHP5 Certification, OSIdays 2010 Chennai
Cookies •Cookies with PHP  Setcookie (Cookie value is encoded automatically)  Setrawcookie (Cookie value is not encoded) How many HTTP requests are required to determine, without JavaScript, whether a client supports cookies or not?
PHP 4/5 Differences •New Error Level E_STRICT •Object Oriented Programming  Public, private, protected  Constructor (__construct)  Destructor (__destruct)  No assignments to $this within a class!  Clone (copy of object  $new = $old (Create reference)  == (Compare all object properties  === (Compare whether two objects are same object)
Quiz • To destroy one variable within PHP session, you should use which method is PHP5 – Use session_destroy() function – Use session_unset() function – Unset the variables in $_SESSION using unset – Any of the above are applicable in PHP5 Zend PHP5 Certification, OSIdays 2010 Chennai
Files, Streams, Network  Two type of file functions  Functions that works with file resource f* () (e.g. Fopen, fclose) Functions that works file name file* () (e.g. file_get_contents)   Which of file function does not exists?  file_get_contents  file_put_contents  file_appends_contents  filesize
Files Which PHP function is (more or less) emulated by this code?
Files  What is the name of the PHP function that reads one line out of a file?  File Operations  Copy  Rename  Unlink  Rmdir  Sockets  Create sockets with fsockopen
XML and Web Services XML   eXtensible Markup Language  Simple rules: Must be well-formed and valid  Universal file format  Usually a special dialect is used in the real world
SimpleXML  "simple" access to XML data from PHP  OOP access for XML data  Elements become object properties  Attributes can be accessed via associative arrays  $xml = simplexml_load_string('<?xml...');  $xml = simplexml_load_file('file.xml');  $xml = new SimpleXMLElement('<?xml...');  simplexml_import_dom() converts a DOM node into a simpleXML object
Quiz • The method used to create a new node to be added into an XML document using DOM is the ____________ method. Zend PHP5 Certification, OSIdays 2010 Chennai
Web Services  Technology for machine-to-machine communication  Not a new idea, but standardization led to success in the real world  Based on XML  Some special formats and protocols exist
Web Services  SOAP Request and Response in XML   WSDL  Web Services Description Language  XML format that contains all information about a web service  Where  Which methods  Data Types  Return values
Web Service  Create a Web Service  Create class with business logic  Register with Soap Server  $soap = new SoapServer('file.wsdl');  $soap->setClass('{class_name}');  Consume web service  $soap = new SoapClient('file.wsdl');  Call methods by $soap->{method_name} or  $soap->__soapCall('myMethod', array('Hello!'));
Databases  Save Data  efficient storage efficient access   Querying using SQL  Exam is database independent!  No special SQL dialect  No special SQL functions
Databases  Primary keys  Foreign keys  Primary key from another table  Enables relational databases  Create Database  Insert/Updat/Delete data  Sorting/Grouping  Aggregation  Joins
Databases •tab1 contains the IDs 1 to 8. tab2 contains the IDs 5 to 10. •What is the output of the following SQL query? •SELECT COUNT(*) FROM tab1 INNER JOIN tab2 ON tab1.ID <> •tab2.ID
Security  All input (from the outside) is (potentially) evil  Filter/validate input Escape output   Trust no data from the outside!  GET/POST data  Cookies  HTTP Headers
Security •Is there a potential security vulnerability in this code?
Security  XSS  Cross-Site Scripting  Injection of HTML, CSS or script code into a page  Especially dangerous: JavaScript
Security  CSRF  Cross-Site Request Forgeries  Creates HTTP requests  Website trusts logged-in users  Attacks are usually executed via iframes or via XMLHttpRequest requests or <script>, <object>, <embed>, <img>, ...  Attacker employs user‘s browser to execute requests on the attacker‘s behalf  <img src="http://shop.xy/buy.php?item_id=123&quantity=1" />  Countermeasures  Use unique token in the form  Require re-login before "dangerous" operations
Security •Is there a potential security vulnerability in this code?
Security  SQL Injection  SQL code is injected into the SQL query  Countermeasures  Prepared statements  Database specific escape functions (mysqli_real_escape_string)
Security  Sessions Attacks  Session Hijacking  Session ID is stolen  Session Fixation User gets a "fixed" session ID (usually via an specially crafted URL)   Countermeasures  Change session ID prior to "critical" operations using session_regenerate_id()  Short session timeout  Use PHP configuration setting session.use_only_cookies
Security  Code Injection  allow_url_fopen = Off in php.ini Another type of code injection can be done when using dynamic data in calls to  system() et al.  Secure Configuration  display_errors = Off  log_errors = On  error_reporting = E_ALL error_reporting = E_ALL | E_STRICT   Secure Password  Use md5 or sha1
Questions?
Thank you for your time and Attention!! Zend PHP5 Certification, OSIdays 2010 Chennai

Zend PHP5 Certification

  • 1.
    Zend PHP5 Certification Presented by – Rakesh Kumar, Rajul Gupta, and Ankur Aeran OSSCube
  • 2.
    Who we are? •Rakesh Kumar – Senior project manager – PHP and related frameworks/Products, Senior consultant and trainer – MySQL, Started as PHP Developer • Rajul Gupta – Senior consultant – CRM – PHP evangelist and ZCE • Ankur Aeran – Tech Lead – Drupal – ZCE, First Zend Framework Certified (India) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 3.
    Why certification? • Industry-widestandard and a measure of distinction • Certification is recognition of a set of capabilities that the person taking the test has developed • ZCE certification helps other people (e.g., potential • employers) answer questions like: – “How predictably is the person likely to perform when applying PHP 5 technology to a business problem?” – “Has this applicant reached a pre-defined minimum standard of experience to undertake professional quality work?” Zend PHP5 Certification, OSIdays 2010 Chennai
  • 4.
    Preparation tools • Instructorlead Online training – Register via website http://www.zend.com/ – Includes certification voucher • Instructor lead classroom training – Authorized training partners • Zend PHP5 Certification Study Guide • Zend PHP5 Certification online practice exam • http://www.zend.com/en/services/certification/php-5-ce Zend PHP5 Certification, OSIdays 2010 Chennai
  • 5.
    About the exam • Composed of ~70 randomly generated questions • Allowed 90 minutes to answer the questions • Questions cover twelve different topic areas • Questions vary in their degree of difficulty • Encompasses curriculum specified by the Zend PHP Education Advisory Board – Completely neutral – Exam excludes references or questions related to Zend‘s products Zend PHP5 Certification, OSIdays 2010 Chennai
  • 6.
    Taking the exam •Exam administered at a Pearson VUE training center ( http://www.pearsonvue.com/) • Register for the exam via telephone or email – May differ by country; please check online • Bring two IDs, one must have your photo (and both must have your signature) • You will receive “scratch“ paper or an eraseable board for calculations at the time you take the test • You are not permitted to bring any materials into the room with you Zend PHP5 Certification, OSIdays 2010 Chennai
  • 7.
    Questions & Strategies •There are several different types of questions, which we will discuss: • Multiple choice, only one answer is correct – Try to eliminate wrong answers – It makes no difference whether you incorrectly answer a question, or do not answer it at all, so... – Guess! Zend PHP5 Certification, OSIdays 2010 Chennai
  • 8.
    Questions & Strategies •Multiple choice, several answers may be correct – Most of the time you are told the number of answers to select – Based on the number of correct answers, you may be able to eliminate some choices Zend PHP5 Certification, OSIdays 2010 Chennai
  • 9.
    Questions & Strategies Freetext •Most of the time, questions are of this type: – What is the output of the following code? – What is the name of the function/setting/constant/… that does X-Y-Z? • Be careful when entering the answer! – No whitespace, explanations, comments, ... – Use lowercase letters with functions Zend PHP5 Certification, OSIdays 2010 Chennai
  • 10.
    Testing software • Youcan mark questions for review – Be sure to check whether there are any questions marked for review before you submit your test • You can mark questions for comment – If there is something you would like the committee to know about a particular question, please use the Comment option to communicate back with Zend • You can easily navigate back to questions you have marked, but not the others, so remember this feature Zend PHP5 Certification, OSIdays 2010 Chennai
  • 11.
    At the end •You’ll immediately get your test result from the testing center; usually printed out – Passed/Failed • No detailed score – If you fail, you will receive feedback about how you did in each topic area (weak -> strong) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 12.
    Basic exam information •You do not have to code large portions for the exam • You do have to answer freetext questions which may contain variable names, small snippets of code, etc. • You do NOT have to memorize the PHP manual – Technically, there are some places where you do, such as remembering which order the parameters for a given function are • You must analyze PHP code • You must know important PHP functions Zend PHP5 Certification, OSIdays 2010 Chennai
  • 13.
    System information • Thecertification is independent of the operating system and a specific database • A general understanding of related technologies like HTTP or SQL is required • Questions refer to a virtual PHP system with the recommended configuration: – register_globals is Off, magic quotes are off, error reporting is set to E_ALL – errors are displayed (unless otherwise noted) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 14.
    About this session •We will give overview of all 12 topic areas • Major session focus is on some complex questions and how to deal with them • Obviously there is not enough time to cover every detail • But there is enough time to give bird’s eye view and briefly describe what is required for passing the exam Zend PHP5 Certification, OSIdays 2010 Chennai
  • 15.
    The topic areas •PHP Basics • Web Features • Functions • PHP 4/5 Differences • Arrays • Files, Streams, Network • OOP • XML and Web Services • Strings and Regular • Database Expressions • Security • Design and Theory Zend PHP5 Certification, OSIdays 2010 Chennai
  • 16.
    Embedding PHP There areseveral options to embed PHP code in an HTML document <?php <? <% <script language="php"> <?= Do all of these work well in any of the environments? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 17.
    Quiz What is theoutput for the following code? <?php $a=10; ?> <?php=$a?> a)Fatal error b)Parser error c)Warning d)Notice e)10 Zend PHP5 Certification, OSIdays 2010 Chennai
  • 18.
    Basic PHP Elements Variable(case-sensitive) ${‘foo’} Variable Variables $bar = “My Value”; $foo = “bar”; $$foo; Constants define('myPHPVER2', 5.1.0, true); //case insensitive Can we undefine a contstant? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 19.
    Quiz What is theoutput of the following code? echo strlen(‘anb’) * strlen(“anb”); Is the following statement correct? ${"function(){ this is a truely awful name for a variable }"} Is there any difference between echo() and print()? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 20.
    Bitwise Operators Left shift:<< o Multiply by 2, x times (x is the operand after <<) o 3 << 4 == 48 (3 * 2^4 = 3 * 16) Right shift: >> o Divide by 2, x times (x is the operand after <<) o 4 >> 2 == 1 (4 / 2^2 = 4 / 4) • Negate bits: ~ Turns 0s into 1s, 1s into 0s Zend PHP5 Certification, OSIdays 2010 Chennai
  • 21.
    Quiz What is theoutput of the following code? <?php $a = 12; Echo ++$a + $a++ +$a; ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 22.
    Quiz class test{ public function abc() { global $x; $x = 15; echo "In ABC -".$x; } public function pqr() { echo " In PQR -".$x; //Notice x is undefined. } } $testObj = new test(); $testObj->abc(); $testObj->pqr(); echo " Out ".$x;*/ Zend PHP5 Certification, OSIdays 2010 Chennai
  • 23.
    Quiz class test{ global $x; public function abc() { $this->x = 15; echo "In ABC -".$this->x; } public function pqr() { echo " In PQR -".$this->x; } } $testObj = new test(); $testObj->abc(); $testObj->pqr(); echo " Out ".$x;*/ Zend PHP5 Certification, OSIdays 2010 Chennai
  • 24.
    Quiz What is theoutput of the following code? <?php $a = 6; echo ($a % 2) ? ($a%3) : ($a % 4); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 25.
    Declare Functions With (optional)parameters and (optional) return value function myFunction($p) { // do something return $p; } $x = myFunction("ABC"); //$x == "ABC" $x = myFunction(); //warning! If warning then what is the solution? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 26.
    Function Parameters Accessing parameters func_num_args():Number of parameters func_get_arg(nr): Parameter number nr func_get_args(): All parameters as an array function addValues() { $sum = 0; for ($i = 0; $i < func_num_args(); $i++) { $sum += func_get_arg($i); } return $sum; } Zend PHP5 Certification, OSIdays 2010 Chennai
  • 27.
    Variable functions Variable functionswork just like variable variables function xyz() { echo "XYZ"; } $d = "abc"; $abc = "xyz"; $$d(); // $$d() == ${"abc"}() == $abc() == xyz() Zend PHP5 Certification, OSIdays 2010 Chennai
  • 28.
    Arrays Zend PHP5 Certification,OSIdays 2010 Chennai
  • 29.
    Quiz What is theoutput of the following code? <?php $a = array(“1” => 10, 1=> ‘B’, “C”, 2=>’D’); echo count($a); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 30.
    Quiz What is theoutput of the following code? <?php $a = array(); For ($i = 0; $i < 20; $i++) { $a[$i/10] = $i; } echo count($a); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 31.
    Quiz What is theoutput of the following code? <?php echo count ( range( 5.0, 3.0, 0.25)); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 32.
    Built-in function • Remembernames and arguments – Commonly used array function (e.g. array_shift, in_array,is_array) – Checking for value functions – Sorting functions Zend PHP5 Certification, OSIdays 2010 Chennai
  • 33.
    OOP • Class declaration • Inheritance • Interface • Abstract classes • Autoloading • Magic methods • Cloning Zend PHP5 Certification, OSIdays 2010 Chennai
  • 34.
    Quiz Which of thesemay be declared as final? 1.Class 2.Method, 3.Variable Zend PHP5 Certification, OSIdays 2010 Chennai
  • 35.
    Converting Objects IntoStrings - Quiz class myClass { function __toString() { echo 'ABC'; } } $c = new myClass(); echo $c; // ABC • Only works when directly called using echo/print Zend PHP5 Certification, OSIdays 2010 Chennai
  • 36.
    Autoloading If a non-existingclass is instantiated, PHP executes the __autoload() function, if available Parameter: Name of the missing class function __autoload($c) { include_once "./classes/class_$c.php"; } $c = new myClass(); //loads ./classes/class_myClass.php Zend PHP5 Certification, OSIdays 2010 Chennai
  • 37.
    Copying Objects • Objectsare always passed by reference • Cloning an object causes the object itself to be copied instead of passing the reference • Keyword clone $c1 = new myClass(); $c2 = clone $c1; • PHP executes the special method __clone() upon cloning (if available) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 38.
    Serializing Objects • Serializingobjects and arrays with serialize() $s = serialize(array(1, 2, 3)); // $s == 'a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}‘ • De-serializing strings with unserialize() $a = unserialize('a:3:{i:0;i:1;i:1;i:2;i:2;i:3;}'); // $a == array(1, 2, 3) • Upon serialization, the special method __sleep() is executed (if available) • Upon de-serialization, the special method __wakeup() is executed (if available) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 39.
    STRING Zend PHP5 Certification,OSIdays 2010 Chennai
  • 40.
    Looking For Strings Thestrpos() function returns the position of the first occurrence – or false. strpos(haystack, needle) strpos(haystack, needle, starting offset) Pay attention to the data type of the return value! 0 means that there was a match at position zero False means no match was made Zend PHP5 Certification, OSIdays 2010 Chennai
  • 41.
    Quiz What is theoutput of the following code? <?php $url = ‘http://myDomain.com/script.php’; $pattern = ‘http://’ If (strpos($url, $pattern)) { echo ‘URL Found’; } Else { echo ‘URL not found’; } ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 42.
    Substrings substr(string, start, length) Returnsa substring Negative start value: Counting starts at the end of the string What is the output of the following code? <?php Echo substr(‘123456’,-4,-2); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 43.
    Comparing Strings • Operator==: Comparison including data type conversion • Operator ===: Comparison including data type check • strcmp(): Case-sensitive comparison • strcasecmp(): Case-insensitive comparison • Return value of str*cmp(): 0 if equal Not 0 if inequal ($a == $b) * strcmp($a, $a) is equal to ??? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 44.
    Counting Strings • Numberof characters strlen(string) Do not confuse with count() (array function)! • Number of words str_word_count(string) str_word_count(strings, true) yields array with all single words Zend PHP5 Certification, OSIdays 2010 Chennai
  • 45.
    Strings And Arrays •explode(split string, string) Converts a string into an array • implode(glue string, string) Converts an array into a string What is the return value of the following code? <?php Echo count(implode(‘.’,’3 … 2 … 1 … still thinking!’); ?> Zend PHP5 Certification, OSIdays 2010 Chennai
  • 46.
    Formatted Output • printf():Prints a formatted string • sprintf(): Returns a formatted string • vprintf(): Prints a formatted string, placeholder values supplied as an array • vsprintf():Returns a formatted string, placeholder values supplied as an array • fprintf(): Sends a formatted string to a resource Zend PHP5 Certification, OSIdays 2010 Chennai
  • 47.
    Regular Expressions • Aregular expression describes a pattern • Looking for patterns is more powerful than looking for (static) strings, though it comes at a cost to performance • Boundaries ^ (start of a line, though not necessarily start of the string) $ (end of a line , though not necessarily end of the string) A (start of the string) Z (end of the string) b (start or end of a word) B (not start or end of a word) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 48.
    Built-in character classes d(digit) D (no digit) s (whitespace) S (no whitespace) w (letter, digit, underscore) W (no letter or digit or underscore) . (any character) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 49.
    Quantifier * (any numberof times) + (any number of times, at least once) ? (0 or 1) {n} (n times) {n,} (at least n times) {,m} (at max m times) {n,m} (at least n times, at max m times) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 50.
    Pattern matching • preg_match(pattern,string) • Return value: Number of matches But: Search ends after the first match Therefore return value 0 or 1 • Match details: third parameter preg_match($pattern, $string, &$matches) o $matches[0]: Complete match o $matches[1]: First submatch and so on Zend PHP5 Certification, OSIdays 2010 Chennai
  • 51.
    Preg Functions preg_match_all($pattern, $string,$matches): Returns all matches preg_replace(search pattern, replace pattern,string) Zend PHP5 Certification, OSIdays 2010 Chennai
  • 52.
    Design and Theory Zend PHP5 Certification, OSIdays 2010 Chennai
  • 53.
    Problem 1 Problem: Objectaccess to a (relational) database Solution: Active Record • ORM: Object-Relational Mapping Use objects during development The system in the background takes care of the communication with the database Typically, a row in the database would be mapped to an Object Example in the PHP world: Doctrine, Propel Zend PHP5 Certification, OSIdays 2010 Chennai
  • 54.
    Problem 2 • Problem:Create complex objects in a simple way • Solution: Factory • Old code: $db = new MySQLiConnection(); //several times • Hard to migrate to another DBMS! New code: • static function factoryDB() { return new DBConnection('MySQLi'); } • factoryDB() is the factory Zend PHP5 Certification, OSIdays 2010 Chennai
  • 55.
    Problem 3 • Problem:Architectural model for web applications • Solution: MVC • Model Encapsulates business logic and application data • View Outputs model data • Controller Controls the application flow Zend PHP5 Certification, OSIdays 2010 Chennai
  • 56.
    Problem 4 • Problem:Indirect access to an object • Solution: Proxy • Used with many web services implementations $s = new SOAPClient('http://example.com/xy.wsdl'); $s->method(); • The local object behaves like the remote object • The background implementation takes care of communication, etc. Zend PHP5 Certification, OSIdays 2010 Chennai
  • 57.
    Problem 5 • Problem:Only one instance of an object shall be used at any time • Solution: Singleton class SingletonPattern { static $conn = null; static function getConnection() { if ($conn == null) { SingletonPattern::$conn = factoryDB('MySQLi'); } return SingletonPattern::$conn; } Zend PHP5 Certification, OSIdays 2010 } Chennai
  • 58.
    Web Features • Whereis form data put with a GET HTTP request? * Where is form data put with a POST HTTP request? • In the following list, the elements "one" and "three" get selected. • • When submitting the form, which values will be found in $_GET or $_POST? Zend PHP5 Certification, OSIdays 2010 Chennai
  • 59.
    File Uploads •* HTMLelement: <input type="file" /> •* Required attribute in the <form> element: enctype="multipart/form-data" •* $_FILES ( Array keys are name, type, size, tmp_name, error) •* Uploads will be deleted after script execution  Copy away using copy_uploaded_file()  Move away using move_uploaded_file()  Check using is_uploaded_file()
  • 60.
    Quiz • When openinga file in writing mode using FTP handler, what must be done so that file will still be written to the server in the event it previously exists? – Provide contest for fopen() using stream_context_create() – You must delete the file first before uploading a new file – Configure this behavior in php.ini using ftp.overwrite directive – Open the file using w+ mode Zend PHP5 Certification, OSIdays 2010 Chennai
  • 61.
    Cookies •Cookies with PHP  Setcookie (Cookie value is encoded automatically)  Setrawcookie (Cookie value is not encoded) How many HTTP requests are required to determine, without JavaScript, whether a client supports cookies or not?
  • 62.
    PHP 4/5 Differences •NewError Level E_STRICT •Object Oriented Programming  Public, private, protected  Constructor (__construct)  Destructor (__destruct)  No assignments to $this within a class!  Clone (copy of object  $new = $old (Create reference)  == (Compare all object properties  === (Compare whether two objects are same object)
  • 63.
    Quiz • To destroyone variable within PHP session, you should use which method is PHP5 – Use session_destroy() function – Use session_unset() function – Unset the variables in $_SESSION using unset – Any of the above are applicable in PHP5 Zend PHP5 Certification, OSIdays 2010 Chennai
  • 64.
    Files, Streams, Network  Two type of file functions  Functions that works with file resource f* () (e.g. Fopen, fclose) Functions that works file name file* () (e.g. file_get_contents)   Which of file function does not exists?  file_get_contents  file_put_contents  file_appends_contents  filesize
  • 65.
    Files Which PHP functionis (more or less) emulated by this code?
  • 66.
    Files  Whatis the name of the PHP function that reads one line out of a file?  File Operations  Copy  Rename  Unlink  Rmdir  Sockets  Create sockets with fsockopen
  • 67.
    XML and WebServices XML   eXtensible Markup Language  Simple rules: Must be well-formed and valid  Universal file format  Usually a special dialect is used in the real world
  • 68.
    SimpleXML  "simple"access to XML data from PHP  OOP access for XML data  Elements become object properties  Attributes can be accessed via associative arrays  $xml = simplexml_load_string('<?xml...');  $xml = simplexml_load_file('file.xml');  $xml = new SimpleXMLElement('<?xml...');  simplexml_import_dom() converts a DOM node into a simpleXML object
  • 69.
    Quiz • The methodused to create a new node to be added into an XML document using DOM is the ____________ method. Zend PHP5 Certification, OSIdays 2010 Chennai
  • 70.
    Web Services  Technology for machine-to-machine communication  Not a new idea, but standardization led to success in the real world  Based on XML  Some special formats and protocols exist
  • 71.
    Web Services  SOAP Request and Response in XML   WSDL  Web Services Description Language  XML format that contains all information about a web service  Where  Which methods  Data Types  Return values
  • 72.
    Web Service  Create a Web Service  Create class with business logic  Register with Soap Server  $soap = new SoapServer('file.wsdl');  $soap->setClass('{class_name}');  Consume web service  $soap = new SoapClient('file.wsdl');  Call methods by $soap->{method_name} or  $soap->__soapCall('myMethod', array('Hello!'));
  • 73.
    Databases  Save Data  efficient storage efficient access   Querying using SQL  Exam is database independent!  No special SQL dialect  No special SQL functions
  • 74.
    Databases  Primarykeys  Foreign keys  Primary key from another table  Enables relational databases  Create Database  Insert/Updat/Delete data  Sorting/Grouping  Aggregation  Joins
  • 75.
    Databases •tab1 contains theIDs 1 to 8. tab2 contains the IDs 5 to 10. •What is the output of the following SQL query? •SELECT COUNT(*) FROM tab1 INNER JOIN tab2 ON tab1.ID <> •tab2.ID
  • 76.
    Security  All input (from the outside) is (potentially) evil  Filter/validate input Escape output   Trust no data from the outside!  GET/POST data  Cookies  HTTP Headers
  • 77.
    Security •Is there apotential security vulnerability in this code?
  • 78.
    Security  XSS  Cross-Site Scripting  Injection of HTML, CSS or script code into a page  Especially dangerous: JavaScript
  • 79.
    Security  CSRF  Cross-Site Request Forgeries  Creates HTTP requests  Website trusts logged-in users  Attacks are usually executed via iframes or via XMLHttpRequest requests or <script>, <object>, <embed>, <img>, ...  Attacker employs user‘s browser to execute requests on the attacker‘s behalf  <img src="http://shop.xy/buy.php?item_id=123&quantity=1" />  Countermeasures  Use unique token in the form  Require re-login before "dangerous" operations
  • 80.
    Security •Is there apotential security vulnerability in this code?
  • 81.
    Security  SQL Injection  SQL code is injected into the SQL query  Countermeasures  Prepared statements  Database specific escape functions (mysqli_real_escape_string)
  • 82.
    Security  Sessions Attacks  Session Hijacking  Session ID is stolen  Session Fixation User gets a "fixed" session ID (usually via an specially crafted URL)   Countermeasures  Change session ID prior to "critical" operations using session_regenerate_id()  Short session timeout  Use PHP configuration setting session.use_only_cookies
  • 83.
    Security  Code Injection  allow_url_fopen = Off in php.ini Another type of code injection can be done when using dynamic data in calls to  system() et al.  Secure Configuration  display_errors = Off  log_errors = On  error_reporting = E_ALL error_reporting = E_ALL | E_STRICT   Secure Password  Use md5 or sha1
  • 84.
  • 85.
    Thank you foryour time and Attention!! Zend PHP5 Certification, OSIdays 2010 Chennai