Presentation By Hugo Agbonon (@Hugo_Agbonon), created using reveal.js
A title delivered by Zend Technologies if you manage to pass any of their certifications:
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
Parce que Zend Technologies ne fournit ni de ressources pour étudier, ni même l'examen pour passer la certification en français
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.
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
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!
If you're interested by those though, there are certifications focused on them, made by Zend and Sensio Labs
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
There are 10 matters covered by the PHP 5.3 certification:
The sad (?) truth: PHP is interpreted. No compilation breaks.
<?php
$statement = "All statements end with a semi-colon";
// Yes, I know you know that.
?>
<?php // Always works ?>
<? // Only works if short_tags are enabled ?>
<% // Only works if asp_tags are enabled %>
<script language="php">// Always works</script>
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
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
$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;
$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
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 */
$a = 1;
$a == 1; // true
$a == '1'; // true
$a === 1; // true
$a === '1'; // false
$a == '1a'; // true
$a === '1a'; // false
$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)
if
else
elseif / else if
ternary operator ($a = condition? true : false;
)
switch
while
do/while
for
foreach
continue
break
die(), exit()
echo(), print()
return()
empty()
eval()
include, include_once(), require, require_once()
isset(), unset()
list()
In the broadest definition namespaces are a way of encapsulating items
Keyword namespace
Element in the global space (default) : Prepend "\"
Know about php.ini
Know about PHP extensions (simpleXML...)
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 :
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.
$xml = simplexml_load_string($xmlString);
$xml = simplexml_load_file($xmlFilePath);
$xml = new SimpleXMLElement($xmlStringOrPath);
$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
The DOM extension allows you to operate on XML documents through the DOM API with PHP 5
$doc = new DOMDocument();
$doc->loadXML(' ');
$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
simplexml_import_dom()
dom_import_simplexml()
I bet you can guess what those functions do :)
$root->foo->bar['attribute']
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 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
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.
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
Set of architectural principles
Trivia : While preparing this, I learned that a string in PHP can be as long as 2GB
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)
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
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)
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
$a = array('a', 'b', 'c');
$a = ['a', 'b', 'c']; /* PHP 5.4! Not OK! */
$a = array('a' => 1, 'b' => 2, 'c' => 3);
$a = array(0 => 1, 2 => 3, 4, 3 => 4);
print_r($a);
/* Array
(
[0] => 1
[2] => 3
[3] => 4
) */
array_push() / array_unshift()
array_pop() / array_shift()
array_merge()
array_slice()
array_splice()
array_keys() / array_values()
array_key_exists() / in_array()
range()
Learn about sort
!
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
You need to memorize the flags:
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()
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
f*()
functions, which work with a file resource (fopen()
, fclose()
)
file*()
functions, which work with a filename (file_get_contents()
, file_put_contents()
)
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_get_contents
is pretty straightforwardfile_put_contents()
has a third optional parameter which allows you to modifiy a bit its behavior (append / overwrite)file_exists()
file()
None of the other file*
functions have underscores in their names!
Get ready for the surgery...
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
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:
A function is case-insensitive
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
Use global
keyword and $GLOBALS
variable to get visibility on variables which are on the global scope of the current script
$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
class
abstract class
interface
extends
, implements
clone
constant
Visibility : public
(default), protected
or private
Access to properties or methods of the current instance by using $this
Paamayim Nekudotayim!
(and self
, parent
, static
)
__construct()
& __destruct()
__invoke()
__call()
& __callStatic()
__get()
& __set()
__isset()
& __unset()
__sleep()
& __wakeup()
__toString()
__clone()
__autoload()
ArrayIterator
, ArrayObject
)It really is SQL and friends
Nothing specific to a particular database (MySQL, PostgreSQL, Oracle)
Know about basic requests & SQL concepts:
SELECT
, INSERT
, UPDATE
, DELETE
, CREATE TABLE
& DROP
JOIN
(INNER
, LEFT
, RIGHT
)An interface for accessing databases in PHP
You need to be able to use it
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
Apache Module
You need to know the basic configuration options for PHP both as a CGI Binary and as an Apache Module
http://www.myawesomewebsite.com?PHPSESSID=2d7d33cfb69b313eaa80368c3a237855
Don't let your session ids fly away!
session.use_only_cookies
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)
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
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)
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.
$_FILES
Passwords encryption/hashing
SSL
Basically, the parts of PHP which are only useful for the web
A way to preserve certain data across subsequent accesses
A visitor accessing your web site is assigned a unique id, the session id
$_SESSION
Say hello to $_GET
, $_POST
& $_REQUEST
When sending files, don't forget enctype='multipart/form-data'
$_COOKIE
is the star
Along with setcookie
and setrawcookie
header()
to set headers (ex: redirection)
headers_list()
, headers_sent()
, headers_remove()
array_chunk()
, thought I'd share