Mission:ZCE

The PHP 5.3 Certification

Presentation By Hugo Agbonon (@Hugo_Agbonon), created using reveal.js

A foreword...

  • Zend?
  • "ZCE"?
  • PHP 5.3?
  • Vive la France !

Zend?

"The PHP Company"

  • Working with PHP almost since its creation
  • Creators of the parser which used by PHP today: The Zend Engine
  • Main sponsor of the Zend Framework (obviously)
  • Zend Studio, Zend Server, Zend Whatever...

"ZCE"?

Zend Certified Engineer!

A title delivered by Zend Technologies if you manage to pass any of their certifications:

  • The PHP 5.3 Certification
  • The Zend Framework Certification

PHP 5.3?

Come on! 5.4 has been out for months!

Yeah, but Zend Technologies did not upgrade its certification, since there are not enough new additions to PHP 5.4

They may do it when PHP has evolved enough, so maybe with PHP 5.5 (currently in beta) or 5.6

Vive la France!

Pourquoi cette présentation est-elle en anglais ?

Parce que Zend Technologies ne fournit ni de ressources pour étudier, ni même l'examen pour passer la certification en français

The certification

How the hell can I get that?

Zend Technologies advises to have done at least 2 years of PHP development before taking the exam

The exam can be taken at almost any time of the year in exam centers. A few of them are in Paris.

How hard is it?

It is HARD

You should at least read the Zend PHP 5.3 Certification Study Guide to get familiar with the type of questions asked

What is it really about?

It's a QCM testing covering 10 different matters and pretty much every aspect of PHP

70 questions, 90 minutes

Emphasis on code analysis, common code elements

To pass, you need a passing score in every matter

Whether you pass or fail the exam, you won't know your score

If you fail, you'll get an indication about the subjects you should work for your next try

You won't get any other review of your exam!

What is it NOT about?

  • It's NOT a certification for the Zend Framework!
  • It's NOT a certification about Symfony either!

If you're interested by those though, there are certifications focused on them, made by Zend and Sensio Labs

Why the hell would I want that?

  • Because as a professional developer, you want recognition of your skills by an international organization
  • Zend Certified Engineers get:
    • A pretty diploma
    • Nice-looking badges for your resume
    • A few other advantages
    • First and foremost: A title recognized internationally by PHP professionals
  • By the way, if you pass or at least talk about it, the title becomes better-known and recognized in France :)

Random notes...

Studying can be boring

You probably already know a lot of things

You'll have to learn a lot of other things. Some by heart

You'll have to deal with "coding horrors" you'd think you'd never see in real code

At the end of it all, you should be able to understand PHP code better and faster than before

OK, let's go!

There are 10 matters covered by the PHP 5.3 certification:

  1. Basics
  2. Data Formats and Types
  3. Strings
  4. Arrays
  5. Input / Output
  6. Functions
  7. Object-Oriented Programming
  8. Databases
  9. Security
  10. Web Features

1. Basics

The sad (?) truth: PHP is interpreted. No compilation breaks.

Syntax

The beginning of everything

<?php
$statement = "All statements end with a semi-colon";
// Yes, I know you know that.
?>

By the way, how do I open my PHP tags ?

<?php // Always works ?> 
<? // Only works if short_tags are enabled ?>
<% // Only works if asp_tags are enabled %>
<script language="php">// Always works</script>

Variables

We love our $

$oneTree = 1;
$1Tree = 1;  // Syntax error. Bam.
$_1Tree = 1;
$OneTree = 1;

Variables names start with $, then a letter or an underscore, then can contain numbers

Constants

const GREATEST_COMPANY = 'Davidson Consulting';
define('GREATEST_COMPANY', 'Davidson Consulting');

No $, UPPERCASE (by convention), then same rules

"Magic" constants (__FILE__ for exemple) are defined by PHP

Amazing assignments

$a = 1; /* $a now equals 1. I hope you are not lost. */
$a += 1; /* $a now equals 2 */
$a -= 1; /* $a now equals 1 */
$a <<= 1; /* $a now equals 2 */
$a >>= 1; /* $a now equals 1 */
$a .= " result"; /* $a now equals "1 result" */
$a = 1;
$b = &a;
$b++; // $a now equals 2, $b is a reference to $a;

The wonderful world of binary numbers

$a = 3 % 2; // $a = 1
$a = 2 << 2; // $a = 8
$a = 4 >> 2; // $a = 0
$a = 6 & 2; // $a = 2
$a = 3 | 1; // $a = 3
$a = 3 ^ 1; // $a = 2
$a = ~8; // $a = -9
$a = ~0; // $a = -1

By the way...

Can you tell me what $a is worth at the second and third line of this code ?

$a = 1;
echo $a++;  /* 1 */
echo ++$a;  /* 3 */

One equal, two equals, three equals...

$a = 1;
$a == 1;  // true
$a == '1';  // true
$a === 1;  // true
$a === '1';  // false
$a == '1a';  // true
$a === '1a';  // false

Fun with math

$a = 1 + 1; // 2
$a = 1 + "1"; // 2
$a = 1 + "un"; // 1
$a = 1 + "1 un"; // 2
$a = 1 + "un 1"; // 1
$a = 1 + 1 . 1 + 1; // 22 (priority to arithmetical operations)

Keep the control

  • if
  • else
  • elseif / else if
  • ternary operator ($a = condition? true : false;)
  • switch
  • while
  • do/while
  • for
  • foreach
  • continue
  • break

Language constructs

  • die(), exit()
  • echo(), print()
  • return()
  • empty()
  • eval()
  • include, include_once(), require, require_once()
  • isset(), unset()
  • list()

Namespaces

In the broadest definition namespaces are a way of encapsulating items

Keyword namespace

Element in the global space (default) : Prepend "\"

More and more "basic" stuff...

Know about php.ini

Know about PHP extensions (simpleXML...)

2. Data Formats and Types

XML

eXtensible Markup Language

You need to know how to manipulate it with PHP

PHP has an extension to allow the parsing of XML documents : libxml

2 main extensions to operate on XML documents :

  • SimpleXML
  • DOM

SimpleXML

Let's quote the PHP manual :

The SimpleXML extension provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.

Creating a SimpleXML object

$xml = simplexml_load_string($xmlString);
$xml = simplexml_load_file($xmlFilePath);
$xml = new SimpleXMLElement($xmlStringOrPath);

Accessing to a SimpleXML object

$quizz = new SimpleXMLElement(
	'<?xml version="1.0" encoding="utf-8" ?>
	<quizz>
		<questions>
			<question type="general" >What is PHP\'s logo?</question>
			<question type="general" >What does PHP mean?</question>
		</questions>
	</quizz>'
);
echo $quizz->questions->question[1]; // What does PHP mean now?
echo $quizz->questions->question[1]['type']; // general

The SimpleXMLElement class has useful helpers methods to get information about the document

DOM

Document Object Model

Same helpful guy we're using to build HTML pages !

The DOM extension allows you to operate on XML documents through the DOM API with PHP 5

Creating a document

$doc = new DOMDocument();
$doc->loadXML('');

Accessing to a document's nodes

$quizz = new DOMDocument();
$quizz->loadXML(
	'<?xml version="1.0" encoding="utf-8" ?>
	<quizz>
		<questions>
			<question type="general" >What is PHP\'s logo?</question>
			<question type="general" >What does PHP mean?</question>
		</questions>
	</quizz>'
);
echo $quizz->getElementsByTagName('question')->item(1)->textContent; // What does PHP mean now?
echo $quizz->getElementsByTagName('question')->item(1)->getAttribute('type'); // general

And now, together !

simplexml_import_dom()
dom_import_simplexml()

I bet you can guess what those functions do :)

That's nice and all...

But outside of the need to learn this for the exam, which one should I use?

Well, someone asked this on Stack Overflow.

SimpleXML

  • is for simple XML and/or simple UseCases
  • limited API to work with nodes (e.g. cannot program to an interface that much)
  • all nodes are of the same kind (element node is the same as attribute node)
  • nodes are magically accessible, e.g. $root->foo->bar['attribute']

DOM

  • is for any XML UseCase you might have
  • is an implementation of the W3C DOM API (found implemented in many languages)
  • differentiates between various Node Types (more control)
  • much more verbose due to explicit API (can code to an interface)
  • can parse broken HTML
  • allows you to use PHP functions in XPath queries

XPath queries?

XPath is a query language used to point to different parts of an XML document

With SimpleXML : $xml->xpath('/questions/question')

With DOM and the class DOMXPath

As one or two questions in the exam may require understanding XPath queries, it's recommended that you get familiar with it

JSON : JavaScript Object Notation

JSON has rapidly gained popularity over the last few years

Less verbose than XML, equally useful to share data

The extension is loaded in PHP by default

Keeping it simple

echo json_encode(array('a' => 'b', 'c' => array('d, e'), 1));
/* {"a":"b","c":["d, e"],"0":1} */
print_r(json_decode('{"a":"b","c":["d, e"],"0":1}', true));
/*
Array
(
	[a] => b
	[c] => Array
		(
			[0] => d, e
		)
	[0] => 1
)
*/

You can parse then manipulate JSON as easily as you can manipulate any array.

Client/Server communication

SOAP

Simple Object Access Protocol

Protocol to implement webservices, relies on XML

PHP has an extension which can be used to write SOAP servers and clients

REST

Set of architectural principles

Use of HTTP verbs (GET, POST, PUT, DELETE)

3. Strings

Fun with strings

Trivia : While preparing this, I learned that a string in PHP can be as long as 2GB

Creating a string

Simple quotes or double quotes, double quotes interpretes more stuff (like variables)

HEREDOC

$str = <<<DELIMITER
HEREDOC is great if you want
	the text stored in the variable
		to be exactly as in the code
	(plus, $variables are interpreted)
DELIMITER;

NOWDOC

<<<'DELIMITER'
Pretty much the same
	except that $variables
		will not be interpreted
DELIMITER;

(Don't forget, the end delimiter must NOT be indented)

Manipulating strings all the way

  • trim()
  • str_replace() / str_ireplace()
  • substr()
  • strpos()
  • strlen() / str_word_count()
  • htmlspecialchars() / htmlentities()
  • strcmp() / strcasecmp()
  • strstr() / stristr()
  • strtok
  • similar_text() / levenshtein()
  • soundex() / metaphone()
  • explode() / implode()
  • printf() / sprintf() / vprintf() / vsprintf() / fprintf()

You're going to curse PHP for its lack of consistency in functions names

Trapped with regular expressions

Covered in the exam : PCRE (Perl Compatible Regular Expression)

You need to be able to at least read basic regular expressions

Know the difference between preg_match() (stops after first match) and preg_match_all() (global match)

Encoding

PHP does not natively support multibytes strings

Know about the mb_* string functions to work with multibytes strings

echo strlen('文字列を楽しんで'); // 24
echo mb_strlen('文字列を楽しんで', 'UTF-8'); // 8

4. Arrays

Creating arrays

$a = array('a', 'b', 'c');
$a = ['a', 'b', 'c']; /* PHP 5.4! Not OK! */
$a = array('a' => 1, 'b' => 2, 'c' => 3);

... can be tricky

$a = array(0 => 1, 2 => 3, 4, 3 => 4);
print_r($a);
/* Array
(
    [0] => 1
    [2] => 3
    [3] => 4
) */

Manipulating arrays all the way

  • array_push() / array_unshift()
  • array_pop() / array_shift()
  • array_merge()
  • array_slice()
  • array_splice()
  • array_keys() / array_values()
  • array_key_exists() / in_array()
  • range()

A bit of order

Learn about sort!

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

You need to memorize the flags:

  • SORT_REGULAR
  • SORT_NUMERIC
  • SORT_STRING
  • SORT_LOCALE_STRING
  • SORT_NATURAL
  • SORT_FLAG_CASE

If you don't forget sort...

You won't have any problem with its big family:

  • rsort()
  • ksort() / krsort()
  • asort() / arsort()

Nor about their customizable cousins:

  • usort(), uasort(), uksort()

However, beware their "natural" companions:

  • natsort() / natcasesort()

Comparing

Learn about array_diff:

array array_diff ( array $array1 , array $array2 [, array $... ] )
/* Returns an array containing all the entries from array1 that are not present in any of the other arrays. */

Then you'll know how to work with its family:

  • array_diff_assoc
  • array_diff_key
  • array_diff_uassoc
  • array_diff_ukey

But also with their sworn enemies, the family of array_intersect

array array_intersect ( array $array1 , array $array2 [, array $ ... ] )
	/* Returns the values of array1 whose values exist in all of the arguments. */
  • array_intersect_assoc
  • array_intersect_key
  • array_intersect_uassoc
  • array_intersect_ukey

5. Input / Output

Functions to deal with files

Two main families

  • f*() functions, which work with a file resource (fopen(), fclose())
  • file*() functions, which work with a filename (file_get_contents(), file_put_contents())

Dealing with resources

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

2nd parameter : mode. Type of access required for the string.
Possible modes : r, r+, w, w+, a, a+, x, x+, c, c+, b

Read through a resource with fread(), write to a resource with fwrite (=== fputs)

Don't forget to close your files after usage, using fclose()

file* functions

  • file_get_contents is pretty straightforward
  • file_put_contents() has a third optional parameter which allows you to modifiy a bit its behavior (append / overwrite)
  • file_exists()
  • The ill-named file()

None of the other file* functions have underscores in their names!

Operating on files

Get ready for the surgery...

Other useful I/O functions

  • fgets, fgetcsv, fgetss
  • feof — Tests for end-of-file on a file pointer
  • fpassthru — Output all remaining data on a file pointer
  • fputcsv — Format line as CSV and write to file pointer
  • move_uploaded_file — Moves an uploaded file to a new location
  • readfile - Reads a file and writes it to the output buffer.
  • readdir - Read entry from directory handle
  • tempnam — Create file with unique file name
  • tmpfile — Creates a temporary file

Full reference on the PHP manual

Streams

Row, row, gently down the stream...

The PHP way of generalizing file, network, data compression, and other operations which share a common set of functions and uses

Referenced as scheme://target (Example : http://www.php.net

Composed of:

  • Wrappers (like the http, file wrappers): code which tells the stream how to handle specific protocols/encodings
  • Context (like http headers for an http stream): a set of parameters and wrapper specific options which modify or enhance the behavior of a stream
  • Filters (final piece of code of a stream which can perform operations on data ad it is being read or written)

PHP manual reference

6. Functions

Because, you know, we weren't using functions at all before this section

A function is case-insensitive

Arguments & scope

3 functions : func_num_args(), func_get_arg(argument_number), func_get_args()

Arguments can be passed by value or reference (using &)

Arguments can have default values and be optional

function func($a, &$b, $c = 1) {
		return $b = $a + $b + $c;
	}
	$a = 1; $b = 2; $c = 3;
	echo func($a, $b, $c); // 6
	echo $a . $b . $c; // 163
	echo func(1,2,3); // Fatal error: Only variables can be passed by reference

Scope

Use global keyword and $GLOBALS variable to get visibility on variables which are on the global scope of the current script

Anonymous functions

Some Closure for this section

$a = function() { return 1; }
echo $a();

Most common use : callback functions (remember usort()?)

They can inherit variables from their parent scopes if declared in their header with the keyword use

function ($quantity, $product) use ($tax, &$total) {}

/!\ $this isn't available in closures in PHP 5.3

7. OOP

Quick tour : Keywords

  • Classes: class
  • Abstract classes: abstract class
  • Interfaces: interface
  • Objects
  • Inheritance: extends, implements
  • Cloning: clone
  • Constants: constant

Methods & properties

Visibility : public (default), protected or private

Access to properties or methods of the current instance by using $this

Paamayim Nekudotayim! (and self, parent, static)

Magic methods

  • __construct() & __destruct()
  • __invoke()
  • __call() & __callStatic()
  • __get() & __set()
  • __isset() & __unset()
  • __sleep() & __wakeup()
  • __toString()
  • __clone()
  • __autoload()

PHP manual reference

Misc

  • Type hinting
  • Reflection
  • SPL (ArrayIterator, ArrayObject)

8. Databases

It says "databases", but...

It really is SQL and friends

Nothing specific to a particular database (MySQL, PostgreSQL, Oracle)

So basically...

Know about basic requests & SQL concepts:

  • SELECT, INSERT, UPDATE, DELETE, CREATE TABLE & DROP
  • JOIN (INNER, LEFT, RIGHT)
  • Transactions
  • Prepared statements
  • Primary & foreign keys

PDO

PHP Data Objects

An interface for accessing databases in PHP

You need to be able to use it

PHP Manual reference

9. Security

General settings (supposed during the exam)

  • register_globals to off
  • display_errors to off, log_errors to on
  • allow_url_include to off
  • error_reporting = E_ALL & ~E_DEPRECATED

PHP installations

Apache Module

CGI

You need to know the basic configuration options for PHP both as a CGI Binary and as an Apache Module

Time to fight hackers!

Session hijacking

http://www.myawesomewebsite.com?PHPSESSID=2d7d33cfb69b313eaa80368c3a237855

Don't let your session ids fly away!

  • session.use_only_cookies
  • Regenerate session id / confirm login before important operations
  • Have a short session timeout, provide logout

PHP Manual Reference

XSS

Cross-site Scripting

Basically, someone injects code in your website and uses it to get info / send cookies / do actions (redirection...) to your users

Wikipedia's example is pretty simple and comprehensive

Escape data with htmlentities, htmlspecialchars (strip_tags is not enough)

Sea-surf!... CSRF

Cross-Site Request Forgery

Best self explaining example, from Wikipedia:

Eve: Hello Alice! Look here: <img src="http://bank.example.com/withdraw?account=Alice&amount=1000000&for=Eve" />

Secure your forms with an unique token

Require re-login before sensitive operations

It is not something that happens just to the others!

SQL Injections

Use prepared statements!

Use database-specific functions! (mysqli_real_escape_string)

Use ORMs! (OK, the Zend Study Guide doesn't tell you that, but consider Propel or Doctrine)

Code injection

Long story short: Do not include remote files.

eval is evil (most of the time)

exec(), system(), passthru()... thou shalt avoid

If you must, escapeshellarg() & escapeshellcmd()

There is a /e flag in preg_replace. Don't use it.

Misc

$_FILES

Passwords encryption/hashing

SSL

10. Web Features

Basically, the parts of PHP which are only useful for the web

Sessions

A way to preserve certain data across subsequent accesses

A visitor accessing your web site is assigned a unique id, the session id

$_SESSION

  • session_start()
  • session_destroy()
  • And more

Forms

Say hello to $_GET, $_POST & $_REQUEST

When sending files, don't forget enctype='multipart/form-data'

Cookies

$_COOKIE is the star

Along with setcookie and setrawcookie

HTTP Headers

header() to set headers (ex: redirection)

headers_list(), headers_sent(), headers_remove()

Wrapping-Up

Almost done!

  • HTTP error codes
  • DateTime class
  • Just discovered array_chunk(), thought I'd share
  • Tons, tons of stuff

More resources...

We're done!

Questions?

Thank you for your attention...

And good luck!