zend php5 certification
Upload: osscube-llc-a-global-open-source-enterprise-for-open-source-solutions
Post on 28-Jan-2015
5.653 views
DESCRIPTION
TRANSCRIPT
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-certification/
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• Functions• Arrays• OOP• Strings and Regular
Expressions• Design and Theory
• Web Features• PHP 4/5 Differences• Files, Streams, Network• XML and Web Services• Database• Security
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 errorb)Parser errorc)Warningd)Noticee)10
Zend PHP5 Certification, OSIdays 2010 Chennai
Basic PHP Elements
Variable (case-sensitive)${‘foo’}
Variable Variables$bar = “My Value”;$foo = “bar”;$$foo;
Constantsdefine('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(‘a\nb’) * strlen(“a\nb”);
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
Zend PHP5 Certification, OSIdays 2010 Chennai
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
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
What is the output of the following code?
<?php $a = 12;Echo ++$a + $a++ +$a;?>
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
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;*/
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
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;*/
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
What is the output of the following code?
<?php$a = 6;echo ($a % 2) ? ($a%3) : ($a % 4);?>
Declare Functions
Zend PHP5 Certification, OSIdays 2010 Chennai
With (optional) parameters and (optional) return valuefunction myFunction($p) {// do somethingreturn $p;}
$x = myFunction("ABC"); //$x == "ABC"$x = myFunction(); //warning!
If warning then what is the solution?
Function Parameters
Zend PHP5 Certification, OSIdays 2010 Chennai
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;}
Variable functions
Zend PHP5 Certification, OSIdays 2010 Chennai
Variable functions work just like variable variables
function xyz() {echo "XYZ";}$d = "abc";$abc = "xyz";$$d(); // $$d() ==${"abc"}() ==$abc() ==xyz()
Arrays
Zend PHP5 Certification, OSIdays 2010 Chennai
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
What is the output of the following code?
<?php$a = array(“1” => 10, 1=> ‘B’, “C”, 2=>’D’);echo count($a);?>
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
What is the output of the following code?
<?php$a = array();For ($i = 0; $i < 20; $i++) { $a[$i/10] = $i;} echo count($a);?>
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
What is the output of the following code?
<?phpecho count ( range( 5.0, 3.0, 0.25));?>
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
Zend PHP5 Certification, OSIdays 2010 Chennai
Which of these may be declared as final?
1.Class2.Method,3.Variable
Converting Objects Into Strings - Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
class myClass {function __toString() {
echo 'ABC'; }}$c = new myClass();echo $c; // ABC
• Only works when directly called using echo/print
Autoloading
Zend PHP5 Certification, OSIdays 2010 Chennai
If a non-existing class is instantiated, PHP executes the__autoload() function, if available
Parameter: Name of the missing classfunction __autoload($c) {include_once "./classes/class_$c.php";}$c = new myClass();//loads ./classes/class_myClass.php
Copying Objects
Zend PHP5 Certification, OSIdays 2010 Chennai
• Objects are always passed by reference• Cloning an object causes the object itself to be copiedinstead of passing the reference• Keyword clone$c1 = new myClass();$c2 = clone $c1;• PHP executes the special method __clone() uponcloning (if available)
Serializing Objects
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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() isexecuted (if available)• Upon de-serialization, the special method __wakeup() isexecuted (if available)
STRING
Zend PHP5 Certification, OSIdays 2010 Chennai
Looking For Strings
Zend PHP5 Certification, OSIdays 2010 Chennai
The strpos() function returns the position of the firstoccurrence – 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
Quiz
Zend PHP5 Certification, OSIdays 2010 Chennai
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’;}?>
Substrings
Zend PHP5 Certification, OSIdays 2010 Chennai
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?<?phpEcho substr(‘123456’,-4,-2);?>
Comparing Strings
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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 ???
Counting Strings
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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 allsingle words
Strings And Arrays
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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?<?phpEcho count(implode(‘.’,’3 … 2 … 1 … still thinking!’);?>
Formatted Output
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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
Regular Expressions
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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)
Built-in character classes
Zend PHP5 Certification, OSIdays 2010 Chennai
\d (digit)
\D (no digit)
\s (whitespace)
\S (no whitespace)
\w (letter, digit, underscore)
\W (no letter or digit or underscore)
. (any character)
Quantifier
Zend PHP5 Certification, OSIdays 2010 Chennai
* (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)
Pattern matching
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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 parameterpreg_match($pattern, $string, &$matches)o $matches[0]: Complete matcho $matches[1]: First submatch and so on
Preg Functions
Zend PHP5 Certification, OSIdays 2010 Chennai
preg_match_all($pattern, $string, $matches): Returns all matches
preg_replace(search pattern, replace pattern,string)
Design and Theory
Zend PHP5 Certification, OSIdays 2010 Chennai
Problem 1
Zend PHP5 Certification, OSIdays 2010 Chennai
Problem: Object access to a (relational) databaseSolution: 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 ObjectExample in the PHP world: Doctrine, Propel
Problem 2
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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
Problem 3
Zend PHP5 Certification, OSIdays 2010 Chennai
• Problem: Architectural model for web applications• Solution: MVC
• Model Encapsulates business logic and application data
• View Outputs model data
• Controller Controls the application flow
Problem 4
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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 ofcommunication, etc.
Problem 5
Zend PHP5 Certification, OSIdays 2010 Chennai
• 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;
}}
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