php for web designers
DESCRIPTION
An introduction to PHP covering basic syntax, variables, arrays, looping, functions, includes, SuperGlobals, if/else statements, cookies, forms, and a quick overview of PDO. - Updated 6/6/13 for PSU Web ConferenceTRANSCRIPT
PHP for Web Designers
June 6, 2013
michael stowe
MIKESTOWE
• Open Source Contributor
• Author, Speaker, and Consultant
• 10+ years experience hacking PHP
• Zend Certified PHP 5.3 Software Engineer
• Developer Advocate with Constant Contact
.com @mikegstowe
PURPOSE OF THIS PRESENTATION
The goal of this presentation is not to show
you “cool snippets” but rather to give you a
foundation in PHP to help you use those “cool
snippets” that are already out there, and
customize them to meet your needs.
CONFERENCE ATTENDEES
We’re going to go through A LOT of
information in a very short time (1 hour). I
want to give you a start, but I don’t expect
you to remember EVERYTHING. So don’t
worry, these slides will be posted online along
with my contact information.
MIKESTOWE.COM
WHAT WE’RE GONNA TALK ABOUT
• What is PHP
• Getting Started
• Variables
• If/Else Logical Statements
• Including Files
• SuperGlobals
• Cookies
• Arrays
• Forms & Form Security
• Databases & Database Security
• Functions
• More Resources
WHAT IS PHP
PHP is a server-side programming language
designed by Rasmus Lerdorf in 1995. The
language was originally designed as a
collection of Perl scripts to handle basic
functions (counters, forms, etc) for “Personal
Home Pages.”
WHAT IS PHP
The PHP parser was rewritten by Zeev
Suraski and Andi Gutmans and launched
as the Zend Engine in 1998. Since then
PHP has become the most popular web
language, being used on an estimated
75% of all websites.
WHAT IS PHP
Recent developments in PHP have escalated
its status substantially. PHP 5 offered large
steps in Object Oriented Programming, with
PHP 5.3 being a landmark release, and PHP
5.4 incorporating horizontal architectural
design helping make PHP a truly enterprise
language.
WHAT IS PHP
And a recent survey of decision makers comparing
PHP to other programming languages found:
• 88% said PHP decreased development time
• 81% said it was easier to work with in the cloud
• 79% said it was easier for new developers
• 76% said it was easier to administer
• 65% saw an increase in performance
• 60% found it easier to find resources (staff &
frameworks)
WHAT IS PHP
Today PHP is used by companies including
Google, Facebook, Yahoo, Amazon, eBay,
Wikimedia (Wikipedia), Digg, Flickr, Intel, Best
Buy, CaringBrige, CNN, and more.
PHP also powers WordPress and Drupal, two
of the most popular Blog/ CMS solutions.
WHAT IS PHP
What makes PHP unique from JavaScript,
HTML, or CSS is that it is compiled on the
Server, this means there is no interaction with
the user once the data has been sent. We
can make more calls via Ajax, but once the
data has been sent it cannot be manipulated
without another call.
WHAT IS PHP
And unlike JavaScript, PHP is limited to the
server resources, not the browser resources.
Every time a PHP script is run the server has
to do all of the work running through the
logic, functions, and commands.
SO WHY USE PHP?
The advantage PHP offers is that because it’s
server-side, it is more secure. You are able to
access databases, files, and other resources
without providing the user your credentials,
or making your code base available.
SO WHY USE PHP?
Server-side languages also help reduce the
amount of code you need to transfer to the
browser, making your page load faster,
especially on older browsers and mobile
devices as compared to having to do a ton of
JavaScript to achieve the same effect.
GETTING STARTED
To get started using PHP you will need a basic
editor (Notepad anyone) and a server or
computer with PHP installed. For
development on your personal machine you
can install a prepackaged virtual server such
as WAMP (for Windows) or MAMP (for Mac).
GETTING STARTED
There are also numerous IDE’s out there that
you can use for development purposes. The
advantage to an IDE is that it will highlight
code to make it easier to read and check for
errors as you are typing.
GETTING STARTED
While there are many IDE’s out there, some of the
most recommended include:
• Aptana Studio 3 (free)
• Notepad++ (free)
• Eclipse+PDT (free)
• Netbeans (free)
• Zend Studio
• PhpStorm
• PhpEd
Dreamweaver also offers code highlighting.
GETTING STARTED
Once you have PHP installed and something to
edit PHP scripts with, you can start creating
PHP.
To get started, simply create a script called
yourfile.php and open your code with <?php,
closing it with ?>.
GETTING STARTED
Because PHP is a server-side language it does
not provide any styling for the browser. In
order to return a webpage we will still use
HTML, JavaScript, and CSS to do things client
(browser) side. This code can also be put in
the PHP file outside of PHP brackets.
PHP AND HTML <?php
<html> <head> <title> <?php echo $title; ?> </title> </head> <body> <?php echo 'hello world'; ?> </body> </html>
PHP SYNTAX
There are other types of tags you can use to
declare PHP code, however, you shouldn’t.
Stick with the long form <?php method.
PHP SYNTAX <?php
<?php // Traditional PHP Tag ?> <script language="php"> // Non-‐Traditional -‐ Don't Do This </script> <? // Short Tag -‐ Don't Do This Either ?> <% // ASP Style... Deprecated... I will find you. %>
PHP SYNTAX
Best practice is to use the full <?php /* … */ ?> tags
when writing your code. Short style tags require a
special INI setting to be turned on, so they will not work
on all servers.
ASP style tags also require a special INI directive to be
set, and have been deprecated. They should be avoided
at all costs (no matter how cool they look).
PHP SYNTAX – SHORT ECHO
PHP 5.4 now allows the short echo by default. This looks
like <?=$title; ?>.
However, because PHP 5.4 is so new, and most servers
do not yet support it, you should avoid using the short
echo method in any scripts that may be distributed or
hosted elsewhere.
WAIT! WHAT IS ECHO
Because PHP is a server-side language it operates
on a output buffer, meaning it will not echo
anything out without you explicitly telling it to.
PHP provides multiple methods for echoing or
printing out data. Two of the most popular
statements for this are echo and print (print can
also be used as a function).
PRINT ECHO <?php
<?php // Set a variable!!! $world = 'world'; echo 'hello world'; echo "hello world"; echo 'hello ' . $world; echo "hello $world"; print 'hello world'; print "hello world"; print 'hello ' . $world; print "hello $world"; // All print hello world ?>
VARIABLES
In PHP, setting variables is incredibly easy.
Simply use the dollar sign ($) to declare your text
as a variable, and then use the equal sign (=) to
set it.
Beware using two dollar signs (or the inevitable
variable variable) as well as the double or triple
equal signs (which performs a logical check).
VARIABLES <?php
<?php // Set variables $myvariable = 'hello'; $variable2 = 'world'; // Change variable $myvariable = 'good-night'; // Oops! $myvariable == 'hello'; // (returns FALSE) ?>
IF/ ELSEIF/ ELSE
PHP allows you to run logical checks to perform
different actions based on specific conditions.
The logical operators are:
== Content is equal (ie 0 == false)
=== Content and type are equal (ie int(1) != string(1))
!= Content is Not Equal
!== Content or Type is not Equal
IF/ ELSEIF/ ELSE
PHP allows you to run logical checks to perform
different actions based on specific conditions.
The logical operators are:
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
IF/ ELSEIF/ ELSE
There are a few more (ie bit-wise operators), but
we’re not going into those. You can also add
additional conditions:
&& And
|| Or
IF/ ELSE/ ELSEIF <?php
<?php $text = 'Hello World'; // This returns "text is Hello World" if ($text == 'Hello World') { echo 'text is Hello World'; } ?>
IF/ ELSE/ ELSEIF <?php
<?php $text = 'Hello World'; // This returns "text is Hello World" if ($text == 'Hello World') { echo 'text is Hello World'; } else { echo 'text is not Hello World'; } ?>
IF/ ELSE/ ELSEIF <?php
<?php $a = 1; if ($a == 1 || $a == 2) { echo '$a is equal to 1 or 2'; } elseif ($a !== 3) { echo '$a is not equal to 3 or is not an int'; } else { echo '$a is equal to 3 and is an int'; } ?>
INCLUDING FILES
One of the most convenient features of PHP is the ability
to include or require other files and execute them as PHP
code.
PHP has four main functions for this: include(),
include_once(), require(), require_once().
Note: require() requires the file to exist and be called
in, otherwise it will throw a fatal error. include()
throws a warning which can be suppressed.
INCLUDING FILES <?php
<?php // about_us.php // set menu for use in header.php $menu = 'thismenu.php'; // get header include('header.php'); // get header template ?> <h1>About Us</h1> <p>We are awesome</p> <?php // get footer include('footer.php'); ?>
INCLUDING FILES
include() and require() will execute the
file each time they are called, whereas
include_once() and require_once() will
check to see if the file has already been
included and executed, and if it has, they will
ignore any future calls to the file.
INCLUDING FILES <?php
<?php include('echo_one.php'); include('echo_one.php'); include('echo_one.php'); // echo one included 3 times include_once('echo_one.php'); // echo one NOT included include_once('echo_two.php'); // echo two included ?>
SUPERGLOBALS
SuperGlobals are globals defined by PHP based on
data either being sent to the browser or collected
from the server. These SuperGlobals are accessible
throughout any part of the PHP script.
SuperGlobals include the $_POST, $_GET,
$_REQUEST, $_COOKIE, $_SESSION, $_SERVER, and
$_ENV arrays which each contain special sets of
data.
SUPERGLOBALS
$_POST contains the POST data from form submissions
$_GET contains the parameters from the QueryString
$_REQUEST contains a combination of Post, Get, and
Cookie by default (controlled by INI)
$_COOKIE contains all cookie data sent in the headers
$_SESSION contains the session data (if started)
$_SERVER contains server and client variables
$_ENV contains environmental properties
SUPERGLOBALS <?php
<?php /* * Display the value given for the form * field with a name attribute of * "field_name" */ echo $_POST['field_name']; ?>
SUPERGLOBALS
As a general rule, you should never trust data
provided in the SuperGlobals to be safe or secure.
You should always assume it is tainted.
Likewise, do not depend on $_REQUEST, but rather
use the appropriate SuperGlobal for the source of
the data expected (ie $_POST, $_GET, $_COOKIE).
COOKIES - YUM
Cookies are strings stored on the user’s machine
to help identify them or a specific preference.
For example, you may use a cookie to identify
their favorite theme for your website, to identify
a session, or to remember their username.
COOKIES - YUM
Cookies should NEVER be used to store
passwords, user roles, or information
used by the system to determine user type
(other than a session ID which relies on data tied
to the server. Remember, cookies can be
modified by the user, and should be treated as
“tainted data.”
COOKIES - YUM
Writing to and reading cookies in PHP is very
easy. You can use the setcookie() function to
write to cookies, but you must do it BEFORE the
headers are sent.
Then to read cookies, just use the $_COOKIE
SuperGlobal.
COOKIES- YUM <?php
<?php setcookie('cookie_name', 'cookie_value', time()+6000); // expires after 60 hours echo 'Hi world!'; // But now this doesn't work :( setcookie('mycookie', 'myvalue'); // But we can still edit the cookie // data for internal use:) $_COOKIE['cookie_name'] = 'new_value'; ?>
COOKIES - YUM
To delete a cookie in PHP you will create a cookie
using setcookie() with the exact same name/
key, but with a expiration time in the past.
COOKIES- YUM <?php
<?php setcookie('cookie_name', 'cookie_value', time()+6000); // expires after 60 hours setcookie('cookie_name', '', time()-1); // cookie has been deleted ?>
ARRAYS
One powerful data-type we have in PHP is
arrays. Unlike JavaScript, arrays are not
objects, but are their own entity type.
To declare an array, simply call the array()
function. It’s super easy!
ARRAYS <?php
<?php // Create an array $myArray = array('one', 'two', 'three'); // Append to the array $myArray[] = 'four'; array_push($myArray, 'five'); // Ooh what happens here? array_push($myArray, 'five'); var_dump($myArray); // Echos array('one', 'two', 'three', 'four', 'five', 'five'); ?>
ARRAY KEYS
You can also setup key value pairs with your
array. By default, the array starts with a key of
zero (0) and increments by one for each value.
If you’re used to working with JavaScript it’s very easy to forget this, as arrays in JavaScript start at 1. Remember PHP Arrays start with an index of 0.
ARRAY KEYS <?php
<?php // Build Array $myArray = array('key' => 'value'); // Append $myArray['newKey'] = $value; // Change $myArray['key'] = 'bob'; ?>
ARRAY FUNCTIONS
There are a lot of useful functions for managing your
array, ranging from count() to count the number of
values in an array, array_push(), array_pop(),
array_shift(), array_unshift() to add or remove
items from the array (either to the beginning or end),
array_merge() to merge two arrays, or sort(),
ksort(), usort(), and others to sort your arrays
either by keys or by values.
ARRAY FUNCTIONS
You can also use the explode() and implode()
functions to “explode” strings into an array based
on a separating character, or “implode” arrays
into a string using a separating character. This is
useful for taking a list of items and turning it into
an array for processing, or to a string for display/
storage purposes.
EXPLODE/ IMPLODE <?php
<?php $list = 'red,blue,green,yellow'; $colors = explode(',', $list); // colors is now an array // [0] => 'red', [1] => 'blue', // [2] => 'green', [3] => 'yellow' $pipe = implode('|', $colors); // pipe is now a string // red|blue|green|yellow $colors2 = explode('|', $pipe); // and a new array called colors2 ?>
LOOPING ARRAYS/ ITERATORS
There are several functions to loop through
arrays or iterated objects, including for(),
foreach(), and while().
LOOPING ARRAYS/ ITERATORS <?php <?php $array = array(1 => 'a', 'b', 'c', 'd'); foreach ($array as $key => $value) { echo $value . ' is the ' . $key . 'letter in the abcs'; } $count = count($array); $i = 0; // In this case $i is our key, has to be numeric while ($i < $count) { echo $array[$i] . ' is the ' . $i . 'letter in the abcs'; $i++; // increase $i by one, same as $i = $i + 1; } // Set $i in the loop! for ($i = 1; $i < $count; $i++) { echo $array[$i] . ' is the ' . $i . 'letter in the abcs'; } ?>
LOOPING ARRAYS/ ITERATORS <?php
<?php // Foreach is better for arrays, and faster! But... // While is good for database results! while ($item = mysql_fetch_array($result)) { echo $item['firstName'] . $item['lastName'] . 'is registered <br />'; } ?>
FORMS
One of the primary uses of server-side
languages is form/ data collection. All incoming
data is stored in the $_REQUEST SuperGlobal,
as well as the $_POST or $_GET SuperGlobal
depending on the source (Querystring or a form
with a method of Post).
FORMS
While the $_REQUEST SuperGlobal
contains data from POST, GET, and
Cookies, you should not rely on this
as you do not know WHERE the data is coming
from and it can be used to manipulate your form.
Also, the collection order $_REQUEST uses is set
by each server and may be different than what you
are expecting.
FORMS
Using a form with a method of GET, or without
setting the method to POST is essentially the
same as doing it in the URL:
doForm.php?name=Bob&age=30&submit=Submit
FORMS VIA GET <?php
<form action="doForm.php"> <!-- This form sends data via GET --> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" /><br /> <input type="submit" name="submit" value="Submit" /> </form> <?php // GET SuperGlobal Array // $_GET['name'] => 'Bob'; // $_GET['age'] => '30'; // $_GET['submit'] => 'Submit'; // POST SuperGlobal is Empty ?>
FORMS VIA POST <?php
<form action="doForm.php" method="post"> <!-- This form sends data via GET --> Name: <input type="text" name="name" /><br /> Age: <input type="text" name="age" /><br /> <input type="submit" name="submit" value="Submit" /> </form> <?php // GET SuperGlobal is Empty // POST SuperGlobal Array // $_POST['name'] => 'Bob'; // $_POST['age'] => '30'; // $_POST['submit'] => 'Submit'; ?>
HANDLING FORMS
Now that we have incoming data we can handle
it, first by validating, then by sanitizing the
data, and finally by sending the data
somewhere.
First we will start by checking to make sure we
have data.
HANDLING FORMS <?php
<?php if ($_POST) { // if there is nothing in the $_POST // SuperGlobal this will not be run /** ... ACTIONS HERE ... **/ } ?> <!-- Form can go here -->
HANDLING FORMS
We also want to check and validate that the
data is the data we want. We can do this using
the isset() function, and making sure the
data fits the parameters that we want.
In this case we’re going to use is_numeric()
to check the age.
HANDLING FORMS <?php <?php $error = ''; if ($_POST) { if (!isset($_POST['name'])) { $error .= 'You must enter a name<br />'; } if (!isset($_POST['age']) || !is_numeric($_POST['age'])) { $error .= 'You must enter a valid age<br />'; } if (!$error) { /** SUBMIT **/ } else { // Cut off last BR $error = substr($error, 0, -6); } } ?> <!-- Form can go here -->
HANDLING FORMS
If the form is valid, then we want to sanitize
the data to make sure nothing malicious is
being passed to us (ie XSS attack or attempted
SQL injection).
We will sanitize the data and prepare it to be
emailed to us in this next slide:
HANDLING FORMS
For more on Form Security review
Intro to PHP Security and
PHP Security 101 slides found at
http://www.mikestowe.com/slides
HANDLING FORMS <?php
<?php $error = ''; if ($_POST) { /** ... **/ if (!$error) { $mail = "Form Request" . PHP_EOL . PHP_EOL; // PHP_EOL = end of line, start new line $name = htmlspecialchars(strip_tags($_POST['name'])); $age = htmlspecialchars(strip_tags($_POST['age'])); $mail .= "Name: " . $name . PHP_EOL; $mail .= "Age: " . $age . PHP_EOL; } /** ... **/ } ?>
SENDING EMAIL
Sending a text email is extremely easy in PHP.
To send an email we will use the mail()
function which takes 5 arguments:
• To
• Subject
• Message
• Headers (Optional)
• Additional Params (Optional)
SENDING EMAIL <?php
<?php /** ... **/ if (!$error) { $mail = "Form Request" . PHP_EOL . PHP_EOL; // PHP_EOL = end of line, start new line $name = htmlspecialchars(strip_tags($_POST['name'])); $age = htmlspecialchars(strip_tags($_POST['age'])); $mail .= "Name: " . $name . PHP_EOL; $mail .= "Age: " . $age . PHP_EOL; mail('[email protected]', 'Form Request', $mail, 'FROM: [email protected]'); } /** ... **/ ?> !
ACCESSING THE DATABASE
PHP allows you to connect to and run queries to a
wide range of databases, of which the most popular is
MySQL.
PHP comes with three different libraries for accessing
MySQL including the deprecated mysql functions, the
improved MySQL extension (MySQLi), and PDO or PHP
Data Objects.
MYSQL TUTORIALS
There are several great tools and resources to learn
and use MySQL. Check out some of the sites below to
learn more:
http://www.w3schools.com/sql/
http://www.tizag.com/mysqlTutorial/
PHP DATA OBJECTS
In order to make working with databases easier and
SAFER, PHP Data Objects, or PDO was introduced as a way
of connecting to your database and writing queries.
Queries can be run as raw queries as with the mysql
functions (ie mysql_query()), but PDO allows you to
create a Query template that uses binded variables or
parameters (which are automatically quoted) to prevent
SQL injection (adding security to your application).
USING PHP DATA OBJECTS <?php <?php // Setup PDO Object and Connection Information $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password'); // Build Query Template $stmt = $db->prepare("SELECT * FROM myTable WHERE username = :username AND password = :password"); // Bind and Sanitize Values // You can bind PHP Variables using the bindParam() method instead $stmt->bindValue(':username', $_POST['username'], PDO::PARAM_STR); $stmt->bindValue(':password', $_POST['password'], PDO::PARAM_STR); // Execute and Fetch $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
Running a Select Query
USING PHP DATA OBJECTS <?php
Running an Insert
<?php // Setup PDO Object and Connection Information $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password'); // Build Query Template $stmt = $db->prepare("INSERT INTO myTable (username, password) VALUES (:username, :password)"); // Bind and Sanitize Values // You can bind PHP Variables using the bindParam() method instead $stmt->bindValue(':username', $_POST['username'], PDO::PARAM_STR); $stmt->bindValue(':password', $_POST['password'], PDO::PARAM_STR); // Execute and Fetch $stmt->execute();
USING PHP DATA OBJECTS <?php
Running an Update
<?php // Setup PDO Object and Connection Information $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password'); // Build Query Template $stmt = $db->prepare("UPDATE myTable SET password = :password WHERE username = :username"); // Bind and Sanitize Values // You can bind PHP Variables using the bindParam() method instead $stmt->bindValue(':username', $_POST['username'], PDO::PARAM_STR); $stmt->bindValue(':password', $_POST['password'], PDO::PARAM_STR); // Execute and Fetch $stmt->execute();
FUNCTIONS Functions are groups of code contained within a local
scope… basically, what that means is that you can
run the same code time and time again, without
having to write it 60,000 times.
The local scope allows us to create variables that will
only be used within the function, and will not be
utilized anywhere else.
FUNCTIONS <?php
<?php function echonum($num) { echo $num; } for ($i = 1; $i < 4; $i++) { echonum($num); } // Echos out 1, 2, 3 ?>
FUNCTIONS – MULTIPLE PARAMS <?php
<?php function add($a, $b) { // result is only local $result = $a + $b; // return the result return $result; } $number = add(1, 5); var_dump($number); // prints integer(6); var_dump(isset($result)); // prints bool(false); ?>
FUNCTIONS – GLOBAL VARIABLES <?php
<?php function add($a, $b) { // Call in $result, use global scope global $result; // result is only local $result = $a + $b; } $result = 0; add(1, 5); var_dump($result); // prints integer(6); ?>
CONFERENCE ATTENDEES
QUESTIONS?
Hopefully…
This will give you a good place to start, but one of the best ways to learn is just to get out there and start playing with code on a development environment. There are a lot of places that offer free or low cost hosting where you can build your own site/ applications and learn more. Remember, the journey is just beginning…
More Resources
http://www.php.net - PHP Manual http://www.mikestowe.com - More slides http://www.w3schools.com/php/ - PHP Tutorial http://www.tizag.com/phpT/ - PHP Tutorial http://www.stackoverflow.com - Great place to ask Questions http://www.phpclasses.org - Great collection of PHP scripts
Find a PHP
User Group
http://www.meetup.com http://www.phpusergroups.org/groups.phtml http://www.zend.com/en/company/community/local-php-groups
THANK YOU.
@mikegstowe
visit mikestowe.com/slides for more on PHP and Web Development
@ctct_api
A big thank you to Constant Contact for making this presentation possible