php from soup to nuts course deck
TRANSCRIPT
Introductions
• Who are you / what do you do?
• What experience with PHP?
• Good, Bad, Ugly
• What would you like to learn in this
course?
• Please rate yourself (1-10) on:
• Linux
• PHP
• Software Development
• Web Development
Course Outline (PHP)
• PHP
• Background & Introduction
• Resources & Setup (Linux AMI)
• Control Flow
• Data Types
• Input & Output (inc File Operations)
• Functions
• Web Form Processing
• Variable Scope
• Sessions & Cookies
• XML / SOAP / Web Services
• Best Practices
• Debugging
• Security
Course Outline (Linux, Apache, MySQL)
Linux
• History
• Filesystem
• Basic commands
• Security
Apache
• Request flow
• Config & access control
• Virtual Hosts
• Scaling & Security
MySQL
• History / Basics / Architecture
• Config & Logging
• Database Engines
• SQL Basics
• Debugging
• Scaling & Security
PHP is hyoogeAnd only getting bigger
Why?
It’s the underpinning of may other
software packages (WP,
Drupal,etc) “glue of the web”
Super easy to learn / use
Many repurpose able code samples
on the web
It’s fast (as an Apache module)
It’s powerful (inline scripting)
Requires no compiler (developer)
Easy to link to database
Open source
PHP is a love / hate thingGives you more rope to hang yourself
• Type juggling
• Global namespacing
• Confusing variable scope
It may be “too easy” to use
• Larger % of newbs = larger # of mistakes
• Too many sites “working by accident”
Started as a templating language for the Web
• No OOD, exception handling, core necessities in the beginning
• Lots of legacy junk out there that doesn’t take advantage of PHP5
• Lots of inconsistencies / peculiarities contributed to the evolution & it’s legacy
roots.
Waay too much “spaghetti code” out there
• Blame the developers, not the language
• List of issues at http://www.phpsadness.com/
You’re not the only one
“PHP is many things to many people,
but it's never been everything to
anybody.”
Compared to other LanguagesEasier to use / learn
• May be more flexible (doesn’t impose structure, types)
• Think of the core as a “collection of functions”. A lot of functions.
Specifically written for the web
• You can either write entire scripts in PHP, or just embed the scripting
language in the HTML directly (and Apache will handle the parsing / running
of PHP).
• Most other languages like Python, Ruby, .NET are “general purpose”
• PHP started as web-based & has tried to evolve into “general purpose”
Lots of resources, support, frameworks, libraries & boilerplate code out there
• Especially get familiar with StackOverflow.com & AWS LAMP stacks
About PHPPhp
• Recursive acronym: Hypertext Preprocessor
• Open source scripting language suited for web application
• Server side execution rather than client-side (ie. JavaScript)
• Tight binding to Apache makes it super fast
• Characteristic: somewhat flexible syntax
• Interpreted Language
ServerClient
javascript
browser
php
webserver
Lab #1: Setup LAMP STACK
Please refer to the ‘php-course-lab-instructions’ word document
Make /etc/hosts for us to use
We need to open SGs for port 80
After lab, we’ll investigate phpinfo output in detail, and play with
configuration a bit
Some discussion of PECL / PEAR
Some discussion of firebug
Server & File TransferWe’ll use AWS’ LAMP Stack AMI for our labs
To develop, you can either:
• SSH
– SSH - Secure Shell, a network protocol that allows data to be exchanged using a
secure channel between two networked devices
– SSH is used primarily on Linux and Unix based systems to access shell accounts.
– SSH directly into the server & use vi or emacs to write code directly in the
server
ssh -i phpLabKeypair.pem [email protected]
• SFTP
– SFTP – file transfer protocol (s = secure)
– SFTP is built on a client-server architecture
– Never. Ever. Use unsecured FTP
– Write your code locally & then SFTP up to serverscp -i phpLabKeypair.pem some-file.php [email protected]:/var/www/html/
PHP Basics
<?php
$haystack = 'Hello World!';
$needle = 'orld';
// Use the strpos() function
$position = strpos($haystack, $needle);
echo 'The substring "' . $needle . '" in "' . $haystack . '" begins at character ' . $position;
?>
[ec2-user@domU-12-31-39-0F-26-4E labs]$ php -l hello_world.php
No syntax errors detected in hello_world.php
[ec2-user@domU-12-31-39-0F-26-4E labs]$ php -e hello_world.php
The substring "orld" in "Hello World!" begins at character 7
Basic Code
Lint Checking
Run from command line
PHP Call methodsCan run in one of three ways:
1. Called directly by Webserver (most common)
1. Browse to [your-public-domain]/labs/snippets/hello_world.php
2. Change the file & refresh the page, notice the change
2. Made into executable server-side script
1. Make the file executable (chmod +x)
2. Put “hashbang” path to interpreter (#!/usr/bin/php) at top of script
1. Run with “php –e” (to test)
1. Will obviously fail if requires Webserver params (like form elements, etc)
#!/usr/bin/php
<?php
echo “I’m executable”;
?>
Operators
For list of operators in php, go to:
http://us3.php.net/manual/en/language.operators.php
The list includes:
arithmetic operators (*, /, +, -)
string operators, concatenate with ".", append with ".="
logical operators (&&, ||)
equality operators (==, !=)
Let’s browse there now (go through each)
Variable ScopeLocal Variables
A variable declared in a function is considered local.
It can only be referenced in that function.
When you exit the function in which a local variable has been declared, that
variable and its corresponding value are destroyed.
$x = 2;
function assignx() {
$x = 0;
echo "x inside function is $x <br>";
}
assignx();
echo "x outside function is $x <br>";
Variable Scope (cont'd)Global Variables
Global variables can be accessed in any part of the program
To modify global variable, it must be explicitly declared to be a global in the
function in which it is to be modified.
$x = 2;
function assignx() {
global $x; //this is actually, normally, a horrid idea!
$x = 0;
echo "x inside function is $x <br>";
}
assignx();
echo "x outside function is $x <br>";
Variable Scope (cont'd)Static Variables
Static variable does not lose its value when the function exists.
static-variables.php
function keep_track() {
static $count = 0;
$count++;
echo "$count <br>";
}
keep_track();
keep_track();
keep_track();
Variable Scope (cont'd)Superglobal Variables
Predefined variables
HTTP_USER_AGENT
provide user's browser information
For more examples of similar superglobal variables, go to:
http://us3.php.net/manual/en/reserved.variables.server.php
echo "Your browser is: $_SERVER['HTTP_USER_AGENT']";
Predefined VariablesSuperglobals are built-in variables (always available in all scopes)
$GLOBALS: Container for all superglobals
$_SERVER: Server & execution env info
$_GET, $_POST, $_REQUEST: more on these later
$_FILES: HTTP File Upload vars
$_SESSION: Session vars
$_COOKIE: HTTP Cookies
$_ENV: Environment Vars
$php_errormsg: the last error message from PHP
$argc: #of arguments passed to script (command line)
$argv: Array of arguments pass to script (command line)
Control Structures
if / else / elseif
while
do-while
for
foreach
break
continue
switch
declare
return
require & include (and require_once / include_once)
goto
http://us1.php.net/manual/en/language.control-structures.php
Review
Control flow -- ifControls the flow of execution depending on the specified condition
defined by expression
if (expression) {
statement;
}
if (expression) {
statement;
} else {
statement;
}
if (expression) {
statement;
} else if (expression) {
statement;
} else {
statement;
}
//there’s also this shortcut for an “if loop” which does an if-then-else & returns value
// this is called the ternary operator (?:) & here’s an example
$var = 5;
$varGreaterThanTwo = ($var > 2 ? true : false); // this one returns true
Control flow -- switchUse as variant of if-else combination when need to compare with large number of
values
switch($category) {
case "1":
statement1;
break;
case "2":
statement2;
break;
case "3":
statement3;
break;
case "4":
statement4;
break;
}
Control flow -- whileWhile loop
Specifies a condition that must be met before execution is terminated
while (expression) {
statements;
}
//Example: incremental value
global $i;
$i = 0;
while ($i <= 5) {
echo "$i <br>";
$i++;
}
Control flow -- forStatement which allows code to be repeatedly executed
for (expression1; expression2; expression3) {
statements;
}
//Example: Incremental values
global $i;
for ($i=0; $i<=5; $i++) {
echo "$i <br>";
}
8 PHP Data TypesScalars (single value):
• Integer
• Float
• String
• Boolean
Compound (collections):
• Array
• Object
Special (none of the above):
• Resource
• NULL
http://www.php.net/manual/en/language.types.php
Integers• Whole number
• Can be written in decimal, octal or hexidecimal
(with or without leading +/-)
• Decimal (no leading zeroes): 2013, -834, +15
• Octal (leading zeroes plus sequence of
digits 0-7): 0755 [decimal 493], +020 [decimal
8]
• Hex (begin with 0x, followed by sequence of
hex [0-F] digits): 0xFF [decimal 255], 0x10
[decimal 16], 0xDAD1 [decimal -56017]
Floats (or “reals”)• Number with digits
• (usually) Equivalent to the “double” type in C
(can span range from 1.7E-308 to 1.7E+308
with 15 digits accuracy)
• Can be written in decimal, octal or hexidecimal
(with or without leading +/-)
• “common” floats:
• 3.14, 0.017, -7.1
• Scientific notation:
• 0.314E1 // 0.314*10^1 or 3.14
• 17.0E-3 // 17.0*10^-3 or 0.017
Strings• Sequence of chars of arbitrary length
• Require delimiting with single or double
quotes:
• ‘big dog’, ‘fat hog’, etc
• Dbl quotes interpolate variables inside, like:
“hello $name”
• “.” operator is concatenate (like JS “+”)
• “special chars” require delimiting with double
quotes
Strings (cont’d)
Escape sequence Character Represented
\” Double quotes
\n Newline
\r Carriage return
\t Tab
\\ Backslash
\{ Left brace
\} Right brace
\[ Left bracket
\] Right bracket
\$ Dollar sign
\0 through \777 ASCII char in octal
\x0 through \xFF ASCII char in hex
Strings (cont’d)
$dos_path = 'C:\\WINDOWS\\SYSTEM';
$publisher = 'Tim O\'Reilly';
echo "$dos_path $publisher\n";
C:\WINDOWS\SYSTEM Tim O'Reilly
A single-quoted string only recognizes \\ to get a literal
backslash and \' to get a literal single quote:
Strings (cont’d) - heredoc
function addHeader($page, $title) {
$page .= <<<EOD
<html>
<head>
<title>$title</title>
</head>
<body>
<h1 align="center">$title</h1>
EOD;
//The EOD above must be fully aligned to the left and on
a line of it's own!
return $page;
}
PHP uses “heredoc” syntax “<<<“ to assign long, mulitiline strings to a value
(heredoc.php)
Strings (cont’d)Web Development makes heavy use of strings!!!
• Get very familiar with the string-related functions in PHP ASAP! Especially:
• explode, echo, chop, implode, str_replace, str_split,
strip_tags, strlen, strpos, strstr, strtok, strtolower,
substr, ucfirst, ucwords
• http://us.php.net/manual/en/book.strings.php
Booleans
“The truth." Dumbledore sighed. "It is a beautiful and terrible thing,
and should therefore be treated with great caution.”
• Booleans represent “truth” (true or false). That’s it.
• Often used to determine control flow like:
• If($logged_in) { … }
• In PHP, several values are false:
• The keyword false
• The integer 0
• The floating-point value 0.0
• The empty string ("") and the string "0"
• An array with zero elements
• An object with no values or functions
• The NULL value
• …and if it’s not false, then PHP says it’s true (including Resource values)
• $x= 5; // true
• $x = true; // true
• $y = “”; // false
• $y = false; // false (but written more clearly)
Arrays
$person[0] = "Edison";
$person[1] = "Wankel";
$person[2] = "Crapper";
$creator['Light bulb'] = "Edison";
$creator['Rotary Engine'] = "Wankel";
$creator['Toilet'] = "Crapper";
Hold groups (ordered or unordered) of values
Can be nested
Ordered (indexed):
$array = array(‘banana’, ‘apple’, ‘orange’);
Unordered (associative array):
$array = array(‘name’ => ‘joe’, ‘age’ => 23, ‘likes’ => array(‘baseball’,’php’,’COD’));
Arrays (cont’d)
sort($person);
// $person is now array('Crapper', 'Edison', 'Wankel')
asort($creator);
// $creator is now array('Toilet' => 'Crapper',
// 'Light bulb' => 'Edison',
// 'Rotary Engine' => 'Wankel');
Can sort
Frequently loop over with foreach:
foreach ($person as $name) {
echo "Hello, $name\n";
}
foreach ($creator as $invention => $inventor) {
echo "$inventor created the $invention\n";
}
Hello, Edison
Hello, Wankel
Hello, Crapper
Edison created the Light bulb
Wankel created the Rotary Engine
Crapper created the Toilet
Sorting ArraysSorting is something we’ll have to do frequently.
Let’s review the ‘sorting-nested-associative-arrays.php’ code
Arrays (cont’d)Like strings, you will be using Arrays frequently!
Get familiar with the functions, especially:
array_chunk, array_combine, array_diff, array_flip,
array_intersect, array_key_exists, array_keys, array_map,
array_merge, array_push, array_rand, array_replace, array_search,
array_shift, array_slice, array_unshift, array_values,
array_walk, asort, count, current, in_array, key, ksort, next,
reset, usort
http://us3.php.net/manual/en/book.array.php
Arrays <-> StringsTo convert an array to a string, we use “implode”
To convert a string to an array, we use “explode”
array-strings-conversion.php
$makers = array('volvo','subaru','jeep','ford','chevrolet');
$myCar = $makers[1];
$someOutput = "I own a car made by $myCar";
print('$makers output:' . "\n" . print_r($makers,true) . "\n");
print('$someOutput output:' . "\n" . print_r($someOutput,true) . "\n");
$makersAsString = implode(',',$makers);
$someOutputAsArray = explode(' ',$someOutput);
print('$makersAsString output:' . "\n" . print_r($makersAsString,true) . "\n");
print('$someOutputAsArray output:' . "\n" . print_r($someOutputAsArray,true) . "\n");
Objects
class Person {
// property
var $name = '’;
// function
function name ($newname = NULL) {
if (! is_null($newname)) {
$this->name = $newname;
}
return $this->name;
}
}
OOP and OOD support clean modular design (which equates to code re-use) and
make debugging and maintenance easier.
Since PHP4, PHP has supported Objects
Objects contain data or properties (variables) and functions (or methods) to operate on that
data
Classes are the base unit of OOD.
Objects (cont’d)
$ed = new Person;
$ed->name('Edison');
printf("Hello, %s\n", $ed->name);
$tc = new Person;
$tc->name('Crapper');
printf("Look out below %s\n", $tc->name);
Hello, Edison
Look out below Crapper
To use a class, you make a ‘new’ instance of it, and access properties & methods with
“->”
Objects (cont’d)Object variables and methods can have different scope:
• public (can be accessed by any caller)
• protected (can be accessed only by the class itself & inherited classes)
• private (only accessed by this class, itself)
Objects (cont’d)
<?php
/**
* Define MyClass
*/
class MyClass {
public $public = 'Public';
protected $protected = 'Protected';
private $private = 'Private';
function printHello() {
echo $this->public; // notice the “this” keyword!
echo $this->protected;
echo $this->private;
}
}
$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
?>
Public, private, protected example
Objects (cont’d)
<?php
/**
* Define MyClass2
*/
class MyClass2 extends MyClass {
// We can redeclare the public and protected method, but not private
protected $protected = 'Protected2';
function printHello() {
echo $this->public;
echo $this->protected;
echo $this->private;
}
}
$obj2 = new MyClass2();
echo $obj2->public; // Works
echo $obj2->protected; // Fatal Error
echo $obj2->private; // Undefined
$obj2->printHello(); // Shows Public, Protected2, Undefined
?>
Public, private, protected example
(extended, so now we can override ‘protected’)
Objects (cont’d)Variables and functions can also be ‘static’
Declaring class properties or methods as static makes them accessible without
needing an instantiation of the class.
Static variables & methods accessed with “::” (as opposed to “->”). Like:
$myClass = new Foo;
$myClass->someNonStaticMethod($param1,$param2);
BUT…
Foo::staticMethod($paramA,$paramB); // I need no “instance”!
“::” is also “Paamayim Nekudotayim” (hebrew for “double colon”)… which you
sometimes see in debug messages
Discussion: “Why would we want to use public, protected, private, static”?
“What are some examples of doing this in the real world”?
http://www.php.net/manual/en/language.oop5.static.php
Objects (cont’d)
<?php
class Foo {
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static; // note the syntac for accessor
}
}
class Bar extends Foo {
public function fooStatic() {
return parent::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
‘Static’ example
Objects vs Procedural
<?php
// Procedural Example
// Connect to MySQL
$connection = mysql_connect('localhost', 'harryf', 'secret');
// Select desired database
mysql_select_db('sitepoint', $connection);
// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = mysql_query($sql, $connection);
// Display the results
while ($row = mysql_fetch_array($result)) {
// Display results here
}
?>
<?php
// OOP Example
// Include MySQL class
require_once 'Database/MySQL.php';
// Instantiate MySQL class, connect to MySQL and select db
$db = new MySQL('localhost', 'harryf', 'secret', 'sitepoint');
// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = $db->query($sql); // Creates a MySQLResult object
// Display the results
while ($row = $result->fetch()) {
// Display results here
}
?>
Objects wrap-upOOD & OOP are deep, deep topics. Highly suggest you look deeper into them and in
particular investigate:
• Design Patterns
• Other languages (especially Java, .NET)
• TDD (test driven development) – not really about OOD, but related
• Frameworks which use OOD / OOP
• The latest OOD features available in PHP 5.3 (interfaces, single inheritance, etc)
Being a good object-oriented developer is what sets the hacks apart from the pros.
PHP doesn’t “force” objects on you like other languages, so keep your eye open for
opportunities to both use standard (procedural) PHP and Objects.
Resources
$res = database_connect(); // fictitious function
database_query($res);
$res = "boo"; // database connection automatically closed
// especially make sense inside of functions
// when function closes, reference is freed
function search () {
$res = database_connect();
$database_query($res);
}
PHP Resources are special variables which hold a reference to let PHP interact with
the outside world – things like opened files, database connections, image
canvases, etc
Really integers under the surface
Garbage collected when no longer in use (when last reference goes away)
NULL
<?php
$a = array();
// '==' tests if the value is equal (type is not considered)
// ‘!=‘ tests if the value is NOT equal (and there is also !==)
$dbl_equal_test = ($a == null ? 'true' : 'false');
// '===' tests if both the value and the TYPE are equal
$trpl_equal_test = ($a === null ? 'true' : 'false');
$isnull_test = (is_null($a) ? 'true' : 'false');
print "== test: $dbl_equal_test \n"; // returns true
print "=== test: $trpl_equal_test \n"; // returns false
print "isnull_test: $isnull_test \n"; // returns false
// how can we make the last two tests return true?
?>
NULL represents a variable that has no value
A variable is null if:
• It has been assigned to the constant “NULL”
• It has not been set to any value yet
• It has been unset();
Data Types ReviewBoolean (true or false)
$variable = false; // $variable is false
$variable = 0; // $variable is false
$variable = true; // $variable is true
$variable = 1; // $variable is true
$variable = 5; // $variable is true
Any non-zero value – true
Integer
Whole number, no fractional parts
Maximum supported integer size is typicalla 2^31
Float
Floating-point number -- contains fractional parts.
String
Sequence of character treated as a contiguous group
Type casting
Converting one type to the other
example:
$variable1 = 13;
$variable2 = (double) $variable1; // 13.0
$variable1 = 4.2;
$variable2 = (int) $variable1; // 4 (truncated, not round)
Type juggling
<?php
$foo = “0”; // $foo is a string (ASCII 48)
$foo += 2; // $foo is now an integer (2)
$foo = $foo + 1.3; // $foo is now a float (3.3)
// and now it gets really weird
$foo = 5 + “10 little pigges” // $foo is now an integer again (15)
$foo = 5 + “20 more piggies” // $foo is integer (25)
?>
Data Types wrap up
is_string($var);
is_int($var);
Is_float($var);
is_array($var);
is_resource($var);
is_bool($var);
is_null($var);
is_object($var); // also have “is_a($object, $class)” which tests if it is
exactly a of this class
Choosing the right data type for a variable is key to a program working correctly
Knowing what values equate to true, false, null is key to write functioning code (and
debugging broken code)
Strings & Arrays are used heavily
PHP uses type juggling (kind of like Java autoboxing)
Types can be cast like (int) $this_was_a_float;
‘is_[type]’ methods exist for all the types
http://www.php.net/manual/en/language.types.php
Pop Quiz!What are the 8 data types PHP offers? Which are scalars? Which are complex?
What is ‘public’ visibility in an object?
How can I test if something does not equal something else?
When did php start using objects?
What are the 2 types of arrays we have in PHP? When would I want to use each?
What are the advantages of using objects? When would I want to write an object vs
procedural?
How can I test if both a variables value & type are exact?
What type of loop do we commonly use to parse over arrays? How do you write that?
What is the shortcut for an “if then else (assignment)”?
What are resources and how are they totally different than other data types?
How do I access static object methods or variables?
Why would I ever want to use “static” methods or variables?
What two data types did we say we’ll be commonly using?
What is the airspeed velocity of an unladen african swallow?
What are the two ways PHP represents Floats?
What are the three ways I can represent an INT? What does each look like?
What must I do in PHP to compare an int to a float?
Operators
Let’s review operators & how they are used
Arithmetic
Assignment
Bitwise
Comparison
Error Control
Execution
Increment/Decrement
Logical
String
Array (array-operators.php)
Type
http://www.php.net/manual/en/language.operators.php
ConstantsAn identifier (name) for a simple (and immutable or “unchangeable”) value
Case-sensitive
Are always uppercase (by convention)
define (‘CONSTANT’, ‘value’);
define(‘KEY_ELEMENT’, 1);
define(‘SYNTAX_CHECK’, true);
echo CONSTANT // outputs ‘value’;
echo Constant // outputs ‘Constant’ and issues a notice
//As of PHP 5.3
const CONSTANT = ‘value’;
echo CONSTANT; // outputs ‘value’
Magic ConstantsPHP makes these available to you in any program (useful, especially for error messaging)
Magic constants have two underscores before & after the constant name
__LINE__ current line # of file
__FILE__ full path & filename of the file
__DIR__ directory the file is in
__FUNCTION__ name of the function we’re in
__CLASS__ name of the class we’re in
__METHOD__ name of the class method (class function) we’re in
__NAMESPACE__ the current namespace we’re in
Variable variables ($$)$thatname = ‘something dynamic – I couldn’t know at runtime’
$var = ‘thatname’; // straightforward, but did you know that you can do:
$newvar = $$var; // this will evaluate the contents of $var (thatname) as a variable (which it
is)
variable-variables.php
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
echo $a . "\n"; //Returns Hello
echo $$a . "\n"; //Returns World
echo $$$a . "\n"; //Returns Foo
echo $$$$a . "\n"; //Returns Bar
echo $$$$$a . "\n"; //Returns a
echo $$$$$$a . "\n"; //Returns Hello
echo $$$$$$$a . "\n"; //Returns World
References (&$)$var = 5;
$othervar = $var; // makes a deep copy, each has their own value of 5
$reference = &$var; // makes a reference (pointer) to $var … they both point to the same
thing
refereces.php
http://www.php.net/manual/en/language.references.whatdo.php
$othervar = 5;
$var = $othervar;
$othervar++;
print "var is $var, othervar is $othervar\n";
$reference =& $var; // assign by reference (same as $reference = &$var)
$reference--;
print "var is $var, othervar is $othervar, reference is $reference\n";
unset($reference); // this actually just deletes $reference itself, not $var
print "var is $var, othervar is $othervar, reference is $reference\n";
Error Control (@)When “@” is prepended to an expression in PHP, any error messages that might be
generated by that expression will be suppressed / ignored.
error-control.php
http://www.php.net/manual/en/language.operators.errorcontrol.php
/* Intentional file error */
$my_file = @file ('non_existent_file') or
die ("Failed opening file: error was '$php_errormsg'");
// this works for any expression, not just functions:
$value = @$cache[$key];
// will not issue a notice if the index $key doesn't exist.
Execution Operator (``)Backticks (``) tells PHP to run what’s in the backticks in the linux (or cygwin) shell.
You can even assign the output of the shell to a variable and use it in PHP
http://www.php.net/manual/en/language.operators.execution.php
Ask students for example
<?php
$output = `ls -al`;
echo "<pre>$output</pre>";
?>
PHP FunctionsFunctions can either be:
• Built-in
• STRING functions like: strpos, explode, implode, ucwords, chunk_split
• ARRAY functions like: array_flip, array_map, extract, in_array, sort, pos
• FILESYSTEM functions like: fopen, file_get_contents, chown, is_writeable, mkdir
• MATH functions like: ceil, sqrt, min, log, rand, round
• WEB SERVICE functions like: simple_xml
• http://us2.php.net/manual/en/book.simplexml.php
• …and lots more…
• Review http://us1.php.net/manual/en/ navigation & search for function
• Pick one function, show pieces, code samples
• Lets each take a couple, investigate, & report back with working code
• User Defined (You can make whatever functions you like… do powerful things like):
• Custom file operations / formats (look up GEOIP info given an IP addr)
• Custom complicated variable munging
• Manage shopping cart (may be better with classes, we’ll cover later)
• Manage personalizations (same as “shopping cart”)
• Custom function review
• Implement custom function that extends some behaviour in some way
FunctionsConsist of: (1) Function definition, (2) Function implementation
function definition
------------------------
function function_name (parameters) {
statements;
}
//function definition: converting degrees to radians
function rad($deg_in) {
$result = $deg_in *(pi()/180);
return $result;
}
//function implementation: converting degrees to radians
$radvalue = rad(30.0);
echo "radvalue= $radvalue <br>"; //radvalue= 0.523598775598
function implementation
---------------------------------
//value-returning function:
$value = function_name(parameters);
//non-returning function:
function_name(parameters);
Functions (con’t)PHP already has many of the functions that you’ll need (and some you’ll never
touch). Let’s take a look at some:
htmlspecialchars()
htmlentities()
md5() & sha1()
urlencode()
microtime()
sunrise()
sunset()
checkdate()
strtodate()
file_get_contents() / file_put_contents()
array_map()
filter_var() http://www.php.net/manual/en/filter.examples.validation.php
filter_var / sanitize_varVery useful functions to filter & sanitize things like emails, numbers, strings,
IP addresses, etc.
filter_var.php
// filter email
$email_a = '[email protected]';
$email_b = 'bogus';
if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
echo "This ($email_b) email address is considered valid.";
}
Input to functions• This prints out all numbers between one and 20 (recursion.php)
<?php
function recursion($a) {
if ($a < 20) {
echo "$a\n";
recursion($a + 1);
}
}
recursion($argv[1]);
?>
Comment out ‘recursion’ call & provide a default value
http://us3.php.net/manual/en/functions.user-defined.php
Returning Values
http://us3.php.net/manual/en/functions.returning-values.php
Input• From command-line,
• From Web Server (web-server-input.php)
http://www.php.net/manual/en/reserved.variables.argv.php
<?php
var_dump($argv);
?>
<?php
print ‘GET PARAMS:<br />’;
var_dump($_GET);
?>
<hr>
<?php
print ‘COOKIES:<br />’;
var_dump($_COOKIE);
?>
Add page_loads cookie
Files as Input• This also works on URLs (fread.php)
<?php
// get contents of a file into a string
$filename = "/etc/php.ini";
if(isset($argv[1])) {
$filename = $argv[1];
}
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
print $contents;
?>
Change permissions of file so it’s not readable. What happens?
Browsing URLs?
http://us3.php.net/manual/en/functions.user-defined.php
What about writing to sockets? (fsockopen.php)
Directory operationsopendir($location)
• Creates a handle for the directory
readdir($handle)
• pulls every entry from the handle for processing one by one
• Often wrapped with “while loops” like:
closedir($handle)
• Close it down when done
http://us.php.net/manual/en/book.dir.php
<?php
$handle = opendir(‘~/’);
while($item = readdir($handle)) {
echo “\nitem is: $item”;
}
?>
Outputecho / print
– displaying output to screen
– return void
– identical to print
• theoretically echo would be faster (efficient) as it returns nothing, however, the
difference is impossible to notice. The decision to use is rather stylistic concern.
• Shortcut is <?= $variable ?>
printf() – (printf.php)
– displaying formatted output to screen
– example: printf("01.2f", 43.2); // 43.20
– Modify to print out binary format
http://us.php.net/manual/en/function.sprintf.php
sprintf()
– identical to printf(), but the output is assigned to a string variable
– example:
$var = sprintf("%01.2f",43.2);
echo "$var"; //43.20
Output (Cont’d)flush and ob_flush (flush.php)
– Will write out (and zero) the buffer
– Can be useful to send output to a screen as it comes in
<?php
if (ob_get_level() == 0) ob_start();
for ($i = 0; $i<10; $i++){
echo "<br> Showing line $i";
echo str_pad('',4096)."\n";
ob_flush();
flush();
sleep(2);
}
echo "Done.";
ob_end_flush();
?>
Form Input (basic)Required HTML form
Functions:
• isset - Determines if a variable is set and is not NULL.
• $_POST['variable'] is an associative array of variables passed to the
current script via the HTTP POST method.
• $_POST is a superglobal contains information pertinent to any
parameters passed using the POST method.
– POST is a preferred option (the other option is GET) as it can handle considerably
more data
– A POST request includes a message body in addition to a URL used to specify
information for the action being performed.
– Example of URL encoding is as follow:
Name: Jonathan Doe
Age: 23
Formula: a + b == 13%!
Encoded as:
Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
Input (syntax)Syntax (example):
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
if (isset($_POST['submit']))
{
echo "Hi, " . $_POST['name']. "! <br/>";
}
?>
<form action="formexample.php" method ="post">
<p>
Name: <br/>
<input type = "text" name="name" size ="20" maxlength ="40" value="" />
</p>
<input type="submit" name = "submit" value"Go!" />
</form>
</body>
</html>
Form Input (advanced)$_POST – separate data packet sent with request
• Advantages?
$_GET
• Advantages?
$_REQUEST
• Advantages?
Input (advanced)$_POST – separate data packet sent with request
• Advantages?
• Forms are slightly more secure (do not cache in browser)
• Cleaner URLs
• Can handle more data (browser limits size of GET requests)
$_GET
• Advantages?
• Canned URLs (can be bookmarked, cached)
• (Slightly) Faster
$_REQUEST
• Advantages?
• Refactoring
• Also contains $_COOKIE
General Rules:
• GET if you can (restful, data access only)
• POST when you can’t
• Try to avoid REQUEST
PHP & Web FormsPHP is commonly used to process HTML Web Forms
This obviously requires some knowledge of HTML (and, ideally Javascript)
PHP can handle any HTML input format you throw at it:
• Text
• Checkbox
• Select Box (multiple selections come in as an array)
• Radio Button
• TextArea
• Hidden
• Submit (including image) buttons
• http://www.w3.org/TR/html401/interact/forms.html#h-17.4.1
• Walk through forms, input types in detail
• If time allows, cover html5 input types:
• http://www.w3schools.com/html/html5_form_input_types.asp
• Compare FF (not HTML5) to Chrome (HTML5)
Combo boxExample
Month:
<select name="month">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5" Selected>May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
// how do we make it multi-select?
FileServerClient
php code
files
php code
files
File Reading & Writing
Steps:
(1) Connecting file handler to a file
(2) Capturing file content
(3) Closing file (ending file handler connection to a file)
File Reading
File Reading
//assigning file handler to a file
$file_handler = fopen("filename","mode");
//capturing file content
$var = fgetcsv($file_handler,1000,",");
//closing file
fclose($file_handler);
mode:
r = read only
w = write only
rt = read only, text file
more on modes:
http://us3.php.net/manual/en/function.fopen.php
File Reading (cont'd)The “file” command reads a whole file into an array
$file = file($filename);
$numlines = count($file); // count() returns the # of elements in an array
for($i=0; $i < $numlines; $i++) {
// do something with each line of the file
}
File WritingFile Writing
//assigning file handler to a file
$file_handler = fopen("filename","mode");
//writing file
fwrite($filehandler,"$variable_to_write");
//closing file
fclose($file_handler);
mode:
w = write only, wt = write only, text file, a = append
more on modes:
http://us3.php.net/manual/en/function.fopen.php
Review of HTTP Request /
ResponseWhiteboard what the HTTP request / response cycle looks like
STATELESS protocol
PHP has a very useful function (header) to ‘bounce’ users to other web pages.
This function essentially sends an HTTP header to the browser, instructing it to do
a 301 (redirect) to another web page. This is very useful for things like login /
logout, permission denied, etc.
http://us2.php.net/manual/en/function.header.php
<html>
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
CookiesHTTP uses domain-specific cookies
Client-side files used for caching data
• Usually so we can recognize user when they
return (they persist across sessions)
• …Or personalize info for them.
• Advantages?
When / how are cookies sent to server?
Whiteboard the flow
//cookies in PHP are in the superglobal ‘$_COOKIE’ as an array of k->v pairs
$arrCookies = $_COOKIE;
foreach ($arrCookies as $key =>$value) {
print “cookie $key has value $value\n”;
}
//write a cookie with ‘setcookie();
setcookie(‘logged-in’,true);
//deleting a cookie – maybe not intuitive, ‘set’ to a time in the past
setcookie(‘logged-in’, ‘’, time() – 3600); // deletes the users cookie (sets to a time in the past)
SessionsServer-side state
• Allows user choices to be maintained
• Commonly used in Shopping Carts, etc.
• PHP stores the sessions in either files (default) or database
• Where is this configured?
Requires either:
• Dropping a cookie (session_id) on user
• Sending session_id in request (either GET or POST)
• Not really practical / recommended / used
Whiteboard the flow
SessionsTo use sessions in PHP, you must either:
• set ‘session_auto_start’ to true in /etc/php.in (and then ‘bounce’ your
webserver with a “sudo service httpd restart”). This is turned off
by default!
• start the session in either your authentication code or on every page where
you want a session (session_start() in the code itself).
• Note: to use sessions, you must also have ‘session.use_cookies’ set to
true (true by default), and if you’re using GET param fallback, you may also want to set ‘session.use_trans_id’ to true as well (default is false).
Some sites (like Amazon.com, for example) will invalidate your session when you
“do something important” (like the 1st time you put an item in your cart). In PHP, this can be done with the function “session_regenerate_id()”
Sessions
<?php
// basic code you’d need to have a user logged in or not…
session_start(); // may also be enabled site-wide by php.ini params
if (isset($_SESSION['user'])) {
?>
// logged in HTML and code here
<?php
} else {
?>
// Not logged in HTML and code here
// at this point, you may want to redirect to a ‘login’ page
<?php
}
?>
Date & TimePHP has very rich date & time functions
Let’s review a few of them…
http://us3.php.net/manual/en/ref.datetime.php
Checkdate()
Date()
Date_add()
Strtotime()
Mktime()
Microtime()
Date & Time
// date formatting is awesome!
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
var_dump($today);
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
$today = date("Y-m-d H:i:s"); // 2001-03-10 17:16:18 (the MySQL DATETIME
format)
Date & Time
<?php
// benchmark your code
$time_start = microtime(true);
for ($i=1; $i<=10000; $i++) {
someFunction();
}
$time_end = microtime(true);
$time_diff = $time_end - $time_start;
echo $time_diff." seconds elapsed!";
?>
RegexRegular expressions (regexes) are heavily used in PHP and any text-heavy
processor.
Regexes essentially match patterns in text with a variety of rules, for example:
//The preg_match() function returns 1 if a match is found and 0 otherwise.
if (preg_match("/ell/", "Hello World!", $matches)) {
echo "Match was found <br />";
echo $matches[0];
}
// strong password validation
$password = "Fyfjk34sdfjfsjq7";
// password must have at least 8 characters (?=.{8,})
// contain at least on lower case char (?=.*[a-z])
// one upper (?=.*[A-Z]), and one digit (?=.*\d)
// (?=…) is a “look ahead” assertion – must match somewhere to the right of whatever is to the
// left of the “(“.
if (preg_match("/^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/", $password)) {
echo "Your passwords is strong.";
} else {
echo "Your password is weak.";
}
Regex – ereg vs pregThere are a lot of “ereg” functions as well – these are being deprecated (since
php5.3) & are slower (in general).
They will be REMOVED in PHP6
ereg
eregi_replace
eregi
split
spliti
sql_regcase
If you have these in your code, you may want to do a sitewide search & replace.
Regex – PCREPCRE are the ones to use
preg_filter
preg_grep
preg_last_error
preg_match_all
preg_match
preg_quote
preg_replace_callback
preg_replace
preg_split
http://us2.php.net/manual/en/book.pcre.php
Regex – GroupingsParenthesis (that don’t have a question mark to the right of “(“) tell regex to put the
match into a special var ($1, $1, $3, etc)
my $line = 'First Name: Bob';
$line =~ /^First Name :\s+(\S+)/;
my $first_name = $1;
echo $first_name;
Regex – Character ClassesCharacter classes are sets of characters that can be in a set position.
If line begins with a number, using a combination of the "beginning of string" meta-
character '^' and a character class that represents any numeric character:
/^[0-9]/
//matches a or b
/[ab]/
// matches if NOT a or b (negated)
/[^ab]/
// so…
gr[ae]y matches either gray or grey
// matches any character (note, this is the same as the shorthand “\w” for “word character”:
/[A-Za-z0-9_]/
// repeating character classes: ? (preceding token is optional) * (0 or more times) + (greedy / one or more)
/Feb(ruary)?/ <- matches both Feb & February
/<[A-Za-z][A-Za-z0-9]*>/ <- matches any valid HTML tag without attributes
/<.+>/ <- the “plus” is greedy – it would match AS MUCH AS it can – like <b>hello</b>
/p+/ <- matches one or more of the char “p”
Regex – QuantifiersCharacter classes are sets of characters that can be in a set position.
If line begins with a number, using a combination of the "beginning of string" meta-
character '^' and a character class that represents any numeric character:
/^[0-9]/
// repeating character classes: ? (preceding token is optional) * (0 or more times) + (greedy / one or more)
/Feb(ruary)?/ <- matches both Feb & February
/<[A-Za-z][A-Za-z0-9]*>/ <- matches any valid HTML tag without attributes
/<.+>/ <- the “plus” is greedy – it would match AS MUCH AS it can – like <b>hello</b>
/p+/ <- matches one or more of the char “p”
Regex Replace + SplitRegular expressions (regexes) are heavily used in PHP and any text-heavy
processor.
Regexes essentially match patterns in text with a variety of rules, for example:
// replace y-m-d with m/d/y
echo preg_replace("/(\d+)-(\d+)-(\d+)/", "$2/$3/$1", "2007-01-25");
// split on “word,”
$keywords = preg_split("/[\s,]+/", "php, regular expressions");
print_r( $keywords );
Regex RulesLets review & test some of the rules:
http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/
One of the best resources for Learning Regexes:
http://www.regular-expressions.info/
Try / catch / throwSome errors (like DB connections) can wreak havoc & you want to catch them &
handle gracefully
Use try / catch whenever you have some situation like this, otherwise users see
whacky errors in their browser.
try {
// do something that can go wrong
} catch (Exception $e){
throw new Exception( 'Something really gone wrong', 0, $e);
}
Try / catch / throwSome more examples – in real life, we wouldn’t echo, but would log
try {
$conn = get_db_connection();
$conn->update( "UPDATE user SET email = '$email' WHERE username = '$username'");
} catch (Exception $e) {
throw new Exception( 'Failed to save email ['.$email.'] for user ['.$username.']', 0, $e);
}
}
try {
update_email( 'myusername', '[email protected]');
} catch (Exception $e) {
echo($e->getMessage().'
'.$e->getTraceAsString().'
');
while($e = $e->getPrevious())
echo('Caused by: '.$e->getMessage().'
'.$e->getTraceAsString().'
');
}
Dynamic Sites w/Databases
PHP would be pretty lame without dynamic capabilities
• We could store in flat files, but slow/difficult to manage
Luckily, PHP provides easy connectors to databases.
Although we’ll only show/use MySQL connections, it’s just as easy to add
connections to SQL Server as well (and you’re welcome to do so if you have a
remotely accessible SQL Server machine up & running).
Database Access w/MySQLTwo options in common use:
• MySQLi
• PDO
• PDO preferred, but MySQLi slightly (2.5%) faster in benchmarks.
If you see “mysql_connect()” and “mysql_query()” in your code, you’re doing it
wrong
http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/
PDO vs MySQLiEstablishing Connection
• Ideally you do this via an auto_prepend_file
• http://php.net/manual/en/ini.core.php#ini.auto-prepend-file
PDO usage//connect to mysql
try {
$objDb = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
} catch(PDOException $ex) {
//handle me. (log error, etc)
}
// you can set attributes
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$objDb->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
function getData($objDb,$strSql) {
$objResult = $db->query($strSql);
$intRowCount = $objResult->rowCount();// row count available if needed
return $objResult->fetchAll(PDO::FETCH_ASSOC); // the other option is "fetch" which gets one at a time
}
$strSql = "SELECT * FROM table";
$arrRows = getData($objDb,$strSql);
// get last insert ID
$objDb->query("INSERT INTO table(firstname, lastname) VALUES('John', 'Doe')");
$intInsertId = $objDb->lastInsertId();
// return # of affected rows in update. 'exec' returns # of affected rows rather than PDO stmt
$intAffectedRows = $db->exec("UPDATE table SET field='value'");
//more info at: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
SQL InjectionBasic idea is that SQL looks like this:
SELECT * FROM USER WHERE email = ‘[email protected]’;
If you accept email from a web form, and don’t look for quotes (‘’), users could
enter the following for email: “[email protected]’; UPDATE USER SET email =
‘[email protected]’ WHERE email = ‘[email protected]’;”
Now your website runs this SQL:
SELECT * FROM USER WHERE email = ‘[email protected]’; UPDATE
USER SET email = ‘[email protected]’ WHERE email =
…and you’re wondering why you can’t log as [email protected] the next day!
SQL InjectionBasic idea is that SQL looks like this:
SELECT * FROM USER WHERE email = ‘[email protected]’;
If you accept email from a web form, and don’t look for quotes (‘’), users could
enter the following for email: “[email protected]’; UPDATE USER SET email =
‘[email protected]’ WHERE email = ‘[email protected]’;”
Now your website runs this SQL:
SELECT * FROM USER WHERE email = ‘[email protected]’; UPDATE
USER SET email = ‘[email protected]’ WHERE email =
…and you’re wondering why you can’t log as [email protected] the next day!
There’s more to it than that, though!
• Escaping
• Pattern check
• Dattabase permissions
http://en.wikipedia.org/wiki/SQL_injection
SQL Injection Prevention• Use PDO prepared statements or stored procedures (runs
mysql_real_escape_string)
• Create your own class to escape, handle patterns, etc
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Magic QuotesWhen on, all ' (single-quote), " (double quote), \ (backslash) and NULL
characters are escaped with a backslash automatically. This is identical to
what addslashes() does.
Essentially, PHP “magic quotes” escape any potentially problem characters in any
client-side (web forms, cookies, etc)
This (along with register_globals) were deprecated in 2009 (PHP 5.3) &
completely removed in 2012 (PHP 5.4), but you still see their usage in the wild.
http://www.php.net/manual/en/security.magicquotes.php
If you find code that depends on these two params, here’s a good walkthrough of
how to refactor that code
http://justinklemm.com/fix-replicate-magic-quotes-register-globals-php-5-4/
Best Practices – S/W Dev• DRY – Don’t Repeat Yourself
• KISS – Keep it Simple (make your code clear & readable)
• Choose descriptive,valuable names (for files, variables, functions, objects, etc)
• Don’t trust anyone (especially your users)
• Sanitize all user input
• 70% of vulnerabilities happen at the OS layer
• If in “hack mode”, refactor after you get it working (the lack of dev effort on the
“refactor” part is what gives PHP, particularly, a bad name)
• Comment (especially in line) copiously
• Be specific over general (use $_GET rather than $_REQUEST)
• Test & build a testing team (PHPUnit -- http://phpunit.de/)
• Especially make sure to test what users see (eBay example)
• JS is more heavily used these days – look into Selenium
• “Write code like the person who will be maintaining it is a psycho killer
who knows your address”
Best Practices – PHP
// I’ve seen this more times than I care to remember
$variable = someComplexFunction($param1,$param2,$param3); // really?
Best Practices – PHP• Sane, consistent names for things
• myVarName vs my_var_name
• Don’t clutter up lines with blank “{“ and “}”
• Objects as much as possible
• Get familiar with config & turn on / use error reporting
• Use MVC
• Use PHP long tags (“<?”) also possible
• Cache DB-driven pages (memcached, APC, Zend Cache, Varnish, squid,…)
• Profile your code (xdebug, & some IDEs like NetBeans actually have inherent)
• Try an IDE
• Better debugging, less carpal tunnel, easier visualization / navigation
• ZendIDE (includes a debugger)
Best Practices – names• I Really like the following:
• $blnVar; // bools
• $intVar; // ints
• $fltVar; // floats
• $strVar; // string
• $arrVar; // array
• $objVar; // object
• $resVar; // resources
• $mixVar; // polymorphic (may be an array or string, for example)
Really helps you think about what the var is supposed to be, and helps
maintainers debug much faster.
Best Practices – standards• Whatever conventions you decide, make sure EVERYONE is on board with
them & using them.
• The worst thing ever is a mess of code written 5 different ways by 5 different
developers with 5 different styles.
Best Practices – braces
//connect to mysql
try {
$objDb = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username',
'password');
}
catch(PDOException $ex)
{
//handle me. (log error, etc)
}
Security - PHPIt’s everyone’s job. It only takes one slip (eg, not sanitizing one form field in one
web form) for a complete vulnerability.
• Make sure everyone understands what is vulnerable
• Understand the language & tools you are using
• Brown bag sessions (if not formal training)
• Formal security testing (NOT written by the folks who wrote the code)
• Watch for orphaned phpinfo() calls
• Log issues so that you can resolve (try / catch)
• http://www.php.net/manual/en/security.php <-WALKTHROUGH
• Use Suhosin http://www.hardened-php.net/suhosin/
Don’t make security the least important thing until it becomes the most
important thing!
DebuggingWe know (and hopefully used) all of the following:
• print_r()
• var_dump()
• phpinfo()
• XDebug
• Firebug (Firefox extension)
• FirePHP (debugger)
• Zend Debugger
• PHP internal error reporting
Lots of gold in this thread: http://stackoverflow.com/questions/888/how-do-you-
debug-php-scripts
Debugging – error typesThere are 3 types of errors
• Semantic (syntax)
• Environment (configs)
• Logic (your code)
We’re all “stupid humans”, we all make mistakes