SlideShare uma empresa Scribd logo
1 de 131
PHP from soup to nuts
Title
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 hyooge
And 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 thing
Gives 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 Languages
Easier 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 PHP
Php
• 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 Transfer
We’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 ec2-user@ec2-54-197-58-85.compute-1.amazonaws.com
• 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 server
scp -i phpLabKeypair.pem some-file.php ec2-user@ec2-54-197-58-85.compute-1.amazonaws.com:/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 methods
Can 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)
Comments
Single line
// comment
Multi line
/*
comment
comment
*/
Variable Scope
Local 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 Variables
Superglobals 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 -- if
Controls 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 -- switch
Use 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 -- while
While 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 -- for
Statement 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>";
}
Lab #2: Control Structures
Please refer to the ‘php-course-lab-instructions’ word document
8 PHP Data Types
Scalars (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:WINDOWSSYSTEM';
$publisher = 'Tim O'Reilly';
echo "$dos_path $publishern";
C:WINDOWSSYSTEM 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, $namen";
}
foreach ($creator as $invention => $inventor) {
echo "$inventor created the $inventionn";
}
Hello, Edison
Hello, Wankel
Hello, Crapper
Edison created the Light bulb
Wankel created the Rotary Engine
Crapper created the Toilet
Sorting Arrays
Sorting 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 <-> Strings
To 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, %sn", $ed->name);
$tc = new Person;
$tc->name('Crapper');
printf("Look out below %sn", $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-up
OOD & 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 Review
Boolean (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?
Lab #3: Data Types
Please refer to the ‘php-course-lab-instructions’ word document
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
Constants
An 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 Constants
PHP 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 $othervarn";
$reference =& $var; // assign by reference (same as $reference = &$var)
$reference--;
print "var is $var, othervar is $othervar, reference is $referencen";
unset($reference); // this actually just deletes $reference itself, not $var
print "var is $var, othervar is $othervar, reference is $referencen";
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 Functions
Functions 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
Functions
Consist 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_var
Very useful functions to filter & sanitize things like emails, numbers, strings,
IP addresses, etc.
filter_var.php
// filter email
$email_a = 'joe@example.com';
$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 "$an";
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 operations
opendir($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”;
}
?>
Output
echo / 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
Lab #4: Input & Output
Please refer to the ‘php-course-lab-instructions’ word document
PHP & Web Forms
PHP 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 box
Example
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?
Lab #5: Web Forms
Please refer to the ‘php-course-lab-instructions’ word document
File
ServerClient
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 Writing
File 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
Lab #6: File Reading
Please refer to the ‘php-course-lab-instructions’ word document
Review of HTTP Request /
Response
Whiteboard 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;
?>
Cookies
HTTP 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 $valuen”;
}
//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)
Sessions
Server-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
Sessions
To 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
}
?>
Lab #7: Cookies & Sessions
Please refer to the ‘php-course-lab-instructions’ word document
Date & Time
PHP 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('it is the jS day.'); // 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 is month'); // 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!";
?>
Lab #8: Date & Time
(benchmarking)
Please refer to the ‘php-course-lab-instructions’ word document
Regex
Regular 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 preg
There 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 – PCRE
PCRE 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 Primer – Meta Chars
Regex – Groupings
Parenthesis (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 Classes
Character 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 – Quantifiers
Character 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 – Shorthand Char
Classes
Regex Replace + Split
Regular 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 Rules
Lets 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/
Lab #9: Regexes
Please refer to the ‘php-course-lab-instructions’ word document
Try / catch / throw
Some 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 / throw
Some 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', 'newmail@foo.com');
} 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/MySQL
Two 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 MySQLi
PDO vs MySQLi
Establishing Connection
• Ideally you do this via an auto_prepend_file
• http://php.net/manual/en/ini.core.php#ini.auto-prepend-file
MySQLi usage
More Examples Here: http://codular.com/php-mysqli
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 Injection
Basic idea is that SQL looks like this:
SELECT * FROM USER WHERE email = ‘user@domain.com’;
If you accept email from a web form, and don’t look for quotes (‘’), users could
enter the following for email: “user@domain.com’; UPDATE USER SET email =
‘hacker@bad.com’ WHERE email = ‘admin@domain.com’;”
Now your website runs this SQL:
SELECT * FROM USER WHERE email = ‘user@domain.com’; UPDATE
USER SET email = ‘hacker@bad.com’ WHERE email =
‘admin@domain.com’
…and you’re wondering why you can’t log as admin@domain.com the next day!
SQL Injection
Basic idea is that SQL looks like this:
SELECT * FROM USER WHERE email = ‘user@domain.com’;
If you accept email from a web form, and don’t look for quotes (‘’), users could
enter the following for email: “user@domain.com’; UPDATE USER SET email =
‘hacker@bad.com’ WHERE email = ‘admin@domain.com’;”
Now your website runs this SQL:
SELECT * FROM USER WHERE email = ‘user@domain.com’; UPDATE
USER SET email = ‘hacker@bad.com’ WHERE email =
‘admin@domain.com’
…and you’re wondering why you can’t log as admin@domain.com 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 Quotes
When 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)
}
Best Practices have real impact
Security - PHP
It’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!
Debugging
We 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 types
There are 3 types of errors
• Semantic (syntax)
• Environment (configs)
• Logic (your code)
We’re all “stupid humans”, we all make mistakes
Your Journey has just begun
rich@quicloud.com - 303-859-3189

Mais conteúdo relacionado

Mais procurados

Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPGuilherme Blanco
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in phpSHIVANI SONI
 
What Is Php
What Is PhpWhat Is Php
What Is PhpAVC
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Muhamad Al Imran
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHPShweta A
 
A History of PHP
A History of PHPA History of PHP
A History of PHPXinchen Hui
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?Nick Belhomme
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHPNick Belhomme
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to phpAnjan Banda
 

Mais procurados (20)

Doctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHPDoctrine 2.0 Enterprise Persistence Layer for PHP
Doctrine 2.0 Enterprise Persistence Layer for PHP
 
Constructor and encapsulation in php
Constructor and encapsulation in phpConstructor and encapsulation in php
Constructor and encapsulation in php
 
What Is Php
What Is PhpWhat Is Php
What Is Php
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
 
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
Php i basic chapter 3 (mardhiah kamaludin's conflicted copy 2013-04-23)
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
 
A History of PHP
A History of PHPA History of PHP
A History of PHP
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
Php basics
Php basicsPhp basics
Php basics
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP
PHPPHP
PHP
 
PHP traits, treat or threat?
PHP traits, treat or threat?PHP traits, treat or threat?
PHP traits, treat or threat?
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Spl in the wild
Spl in the wildSpl in the wild
Spl in the wild
 
Php on Windows
Php on WindowsPhp on Windows
Php on Windows
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Mastering Namespaces in PHP
Mastering Namespaces in PHPMastering Namespaces in PHP
Mastering Namespaces in PHP
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
 

Destaque (20)

P1111318274
P1111318274P1111318274
P1111318274
 
P1151139820
P1151139820P1151139820
P1151139820
 
SOS
SOS SOS
SOS
 
сAshmob at glance
сAshmob at glanceсAshmob at glance
сAshmob at glance
 
Clase 01 06
Clase 01 06Clase 01 06
Clase 01 06
 
Acorde
AcordeAcorde
Acorde
 
Hospitality Industry in Tanzania_HAT Presentation to Hon. Minister Prof Rev1
Hospitality Industry in Tanzania_HAT Presentation to Hon. Minister Prof Rev1Hospitality Industry in Tanzania_HAT Presentation to Hon. Minister Prof Rev1
Hospitality Industry in Tanzania_HAT Presentation to Hon. Minister Prof Rev1
 
Capabilities 8 2 10
Capabilities 8 2 10Capabilities 8 2 10
Capabilities 8 2 10
 
P1151345302
P1151345302P1151345302
P1151345302
 
P1121102462
P1121102462P1121102462
P1121102462
 
P1121138815
P1121138815P1121138815
P1121138815
 
Drug Addiction NICE Guidelines
Drug Addiction NICE GuidelinesDrug Addiction NICE Guidelines
Drug Addiction NICE Guidelines
 
Kingdom nomics book-131205
Kingdom nomics book-131205Kingdom nomics book-131205
Kingdom nomics book-131205
 
P1131210137
P1131210137P1131210137
P1131210137
 
Selectivitat10
Selectivitat10Selectivitat10
Selectivitat10
 
P1121133746
P1121133746P1121133746
P1121133746
 
Open source software
Open source softwareOpen source software
Open source software
 
Ogs designs
Ogs designsOgs designs
Ogs designs
 
Interactive Marketing 2010
Interactive Marketing 2010Interactive Marketing 2010
Interactive Marketing 2010
 
"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercises"PHP from soup to nuts" -- lab exercises
"PHP from soup to nuts" -- lab exercises
 

Semelhante a PHP from soup to nuts Course Deck

php fundamental
php fundamentalphp fundamental
php fundamentalzalatarunk
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of phppooja bhandari
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...anshkhurana01
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Muhamad Al Imran
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Muhamad Al Imran
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit universityMandakini Kumari
 
Tips
TipsTips
Tipsmclee
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHPBUDNET
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13DanWooster1
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbaivibrantuser
 

Semelhante a PHP from soup to nuts Course Deck (20)

Prersentation
PrersentationPrersentation
Prersentation
 
php fundamental
php fundamentalphp fundamental
php fundamental
 
Php introduction with history of php
Php introduction with history of phpPhp introduction with history of php
Php introduction with history of php
 
php
phpphp
php
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
 
Php i basic chapter 3
Php i basic chapter 3Php i basic chapter 3
Php i basic chapter 3
 
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
Php i basic chapter 3 (syahir chaer's conflicted copy 2013-04-22)
 
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
Php i basic chapter 3 (afifah rosli's conflicted copy 2013-04-23)
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
 
PHP MySQL Workshop - facehook
PHP MySQL Workshop - facehookPHP MySQL Workshop - facehook
PHP MySQL Workshop - facehook
 
Php basic for vit university
Php basic for vit universityPhp basic for vit university
Php basic for vit university
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
 
Tips
TipsTips
Tips
 
php 1
php 1php 1
php 1
 
MIND sweeping introduction to PHP
MIND sweeping introduction to PHPMIND sweeping introduction to PHP
MIND sweeping introduction to PHP
 
Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13Upstate CSCI 450 PHP Chapters 5, 12, 13
Upstate CSCI 450 PHP Chapters 5, 12, 13
 
05php
05php05php
05php
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
 
Php training100%placement-in-mumbai
Php training100%placement-in-mumbaiPhp training100%placement-in-mumbai
Php training100%placement-in-mumbai
 

Último

Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.soniya singh
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)Delhi Call girls
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024APNIC
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...SUHANI PANDEY
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...SUHANI PANDEY
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...SUHANI PANDEY
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Servicegwenoracqe6
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceDelhi Call girls
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...SUHANI PANDEY
 

Último (20)

Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
Low Sexy Call Girls In Mohali 9053900678 🥵Have Save And Good Place 🥵
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
Ganeshkhind ! Call Girls Pune - 450+ Call Girl Cash Payment 8005736733 Neha T...
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
VIP Model Call Girls NIBM ( Pune ) Call ON 8005736733 Starting From 5K to 25K...
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort ServiceBusty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
Busty Desi⚡Call Girls in Vasundhara Ghaziabad >༒8448380779 Escort Service
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
Shikrapur - Call Girls in Pune Neha 8005736733 | 100% Gennuine High Class Ind...
 

PHP from soup to nuts Course Deck

  • 1. PHP from soup to nuts Title
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. PHP is hyooge And 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
  • 6. PHP is a love / hate thing Gives 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/
  • 7. You’re not the only one “PHP is many things to many people, but it's never been everything to anybody.”
  • 8. Compared to other Languages Easier 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
  • 9. About PHP Php • 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
  • 10. 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
  • 11. Server & File Transfer We’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 ec2-user@ec2-54-197-58-85.compute-1.amazonaws.com • 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 server scp -i phpLabKeypair.pem some-file.php ec2-user@ec2-54-197-58-85.compute-1.amazonaws.com:/var/www/html/
  • 12. 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
  • 13. PHP Call methods Can 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”; ?>
  • 14. 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)
  • 15. Comments Single line // comment Multi line /* comment comment */
  • 16. Variable Scope Local 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>";
  • 17. 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>";
  • 18. 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();
  • 19. 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']";
  • 20. Predefined Variables Superglobals 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)
  • 21. 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
  • 22. Control flow -- if Controls 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
  • 23. Control flow -- switch Use 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; }
  • 24. Control flow -- while While 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++; }
  • 25. Control flow -- for Statement 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>"; }
  • 26. Lab #2: Control Structures Please refer to the ‘php-course-lab-instructions’ word document
  • 27. 8 PHP Data Types Scalars (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
  • 28. 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]
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. Strings (cont’d) $dos_path = 'C:WINDOWSSYSTEM'; $publisher = 'Tim O'Reilly'; echo "$dos_path $publishern"; C:WINDOWSSYSTEM Tim O'Reilly A single-quoted string only recognizes to get a literal backslash and ' to get a literal single quote:
  • 33. 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)
  • 34. 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
  • 35. 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)
  • 36. 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’));
  • 37. 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, $namen"; } foreach ($creator as $invention => $inventor) { echo "$inventor created the $inventionn"; } Hello, Edison Hello, Wankel Hello, Crapper Edison created the Light bulb Wankel created the Rotary Engine Crapper created the Toilet
  • 38. Sorting Arrays Sorting is something we’ll have to do frequently. Let’s review the ‘sorting-nested-associative-arrays.php’ code
  • 39. 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
  • 40. Arrays <-> Strings To 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");
  • 41. 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.
  • 42. Objects (cont’d) $ed = new Person; $ed->name('Edison'); printf("Hello, %sn", $ed->name); $tc = new Person; $tc->name('Crapper'); printf("Look out below %sn", $tc->name); Hello, Edison Look out below Crapper To use a class, you make a ‘new’ instance of it, and access properties & methods with “->”
  • 43. 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)
  • 44. 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
  • 45. 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’)
  • 46. 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
  • 47. 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
  • 48. 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 } ?>
  • 49. Objects wrap-up OOD & 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.
  • 50. 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)
  • 51. 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();
  • 52. Data Types Review Boolean (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
  • 53. 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)
  • 54. 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) ?>
  • 55. 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
  • 56. 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?
  • 57. Lab #3: Data Types Please refer to the ‘php-course-lab-instructions’ word document
  • 58. 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
  • 59. Constants An 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’
  • 60. Magic Constants PHP 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
  • 61. 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
  • 62. 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 $othervarn"; $reference =& $var; // assign by reference (same as $reference = &$var) $reference--; print "var is $var, othervar is $othervar, reference is $referencen"; unset($reference); // this actually just deletes $reference itself, not $var print "var is $var, othervar is $othervar, reference is $referencen";
  • 63. 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.
  • 64. 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>"; ?>
  • 65. PHP Functions Functions 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
  • 66. Functions Consist 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);
  • 67. 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
  • 68. filter_var / sanitize_var Very useful functions to filter & sanitize things like emails, numbers, strings, IP addresses, etc. filter_var.php // filter email $email_a = 'joe@example.com'; $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."; }
  • 69. Input to functions • This prints out all numbers between one and 20 (recursion.php) <?php function recursion($a) { if ($a < 20) { echo "$an"; 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
  • 70. 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
  • 71. 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)
  • 72. Directory operations opendir($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”; } ?>
  • 73. Output echo / 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
  • 74. 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(); ?>
  • 75. 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
  • 76. 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>
  • 77. Form Input (advanced) $_POST – separate data packet sent with request • Advantages? $_GET • Advantages? $_REQUEST • Advantages?
  • 78. 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
  • 79. Lab #4: Input & Output Please refer to the ‘php-course-lab-instructions’ word document
  • 80. PHP & Web Forms PHP 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)
  • 81. Combo box Example 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?
  • 82. Lab #5: Web Forms Please refer to the ‘php-course-lab-instructions’ word document
  • 83. File ServerClient 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)
  • 84. 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
  • 85. 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 }
  • 86. File Writing File 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
  • 87. Lab #6: File Reading Please refer to the ‘php-course-lab-instructions’ word document
  • 88. Review of HTTP Request / Response Whiteboard 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; ?>
  • 89. Cookies HTTP 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 $valuen”; } //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)
  • 90. Sessions Server-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
  • 91. Sessions To 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()”
  • 92. 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 } ?>
  • 93. Lab #7: Cookies & Sessions Please refer to the ‘php-course-lab-instructions’ word document
  • 94. Date & Time PHP 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()
  • 95. 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('it is the jS day.'); // 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 is month'); // 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)
  • 96. 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!"; ?>
  • 97. Lab #8: Date & Time (benchmarking) Please refer to the ‘php-course-lab-instructions’ word document
  • 98. Regex Regular 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."; }
  • 99. Regex – ereg vs preg There 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.
  • 100. Regex – PCRE PCRE 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
  • 101. Regex Primer – Meta Chars
  • 102. Regex – Groupings Parenthesis (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;
  • 103. Regex – Character Classes Character 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”
  • 104. Regex – Quantifiers Character 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”
  • 105. Regex – Shorthand Char Classes
  • 106. Regex Replace + Split Regular 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 );
  • 107. Regex Rules Lets 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/
  • 108. Lab #9: Regexes Please refer to the ‘php-course-lab-instructions’ word document
  • 109. Try / catch / throw Some 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); }
  • 110. Try / catch / throw Some 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', 'newmail@foo.com'); } catch (Exception $e) { echo($e->getMessage().' '.$e->getTraceAsString().' '); while($e = $e->getPrevious()) echo('Caused by: '.$e->getMessage().' '.$e->getTraceAsString().' '); }
  • 111. 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).
  • 112. Database Access w/MySQL Two 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/
  • 114. PDO vs MySQLi Establishing Connection • Ideally you do this via an auto_prepend_file • http://php.net/manual/en/ini.core.php#ini.auto-prepend-file
  • 115. MySQLi usage More Examples Here: http://codular.com/php-mysqli
  • 116. 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
  • 117. SQL Injection Basic idea is that SQL looks like this: SELECT * FROM USER WHERE email = ‘user@domain.com’; If you accept email from a web form, and don’t look for quotes (‘’), users could enter the following for email: “user@domain.com’; UPDATE USER SET email = ‘hacker@bad.com’ WHERE email = ‘admin@domain.com’;” Now your website runs this SQL: SELECT * FROM USER WHERE email = ‘user@domain.com’; UPDATE USER SET email = ‘hacker@bad.com’ WHERE email = ‘admin@domain.com’ …and you’re wondering why you can’t log as admin@domain.com the next day!
  • 118. SQL Injection Basic idea is that SQL looks like this: SELECT * FROM USER WHERE email = ‘user@domain.com’; If you accept email from a web form, and don’t look for quotes (‘’), users could enter the following for email: “user@domain.com’; UPDATE USER SET email = ‘hacker@bad.com’ WHERE email = ‘admin@domain.com’;” Now your website runs this SQL: SELECT * FROM USER WHERE email = ‘user@domain.com’; UPDATE USER SET email = ‘hacker@bad.com’ WHERE email = ‘admin@domain.com’ …and you’re wondering why you can’t log as admin@domain.com the next day! There’s more to it than that, though! • Escaping • Pattern check • Dattabase permissions http://en.wikipedia.org/wiki/SQL_injection
  • 119. 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
  • 120. Magic Quotes When 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/
  • 121. 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”
  • 122. Best Practices – PHP // I’ve seen this more times than I care to remember $variable = someComplexFunction($param1,$param2,$param3); // really?
  • 123. 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)
  • 124. 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.
  • 125. 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.
  • 126. 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) }
  • 127. Best Practices have real impact
  • 128. Security - PHP It’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!
  • 129. Debugging We 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
  • 130. Debugging – error types There are 3 types of errors • Semantic (syntax) • Environment (configs) • Logic (your code) We’re all “stupid humans”, we all make mistakes
  • 131. Your Journey has just begun rich@quicloud.com - 303-859-3189