LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright ©...

36
LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm) SE3 Lecture Room: 405

Transcript of LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright ©...

Page 1: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Chapter 2: Programming with PHP

Copyright © 2012 by Larry Ullman

Dr. Mogeeb Mosleh

Saturday (9.00-11.00pm) SE3Lecture Room: 405

Page 2: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

What is PHP?• PHP is an acronym for "PHP Hypertext Preprocessor"• PHP is a widely-used, open source scripting language• PHP scripts are executed on the server• PHP costs nothing, it is free to download and use

What is a PHP File?• PHP files can contain text, HTML, CSS, JavaScript,

and PHP code• PHP code are executed on the server, and the result

is returned to the browser as plain HTML• PHP files have extension ".php"

Page 3: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

What Can PHP Do?• PHP can generate dynamic page content• PHP can create, open, read, write, delete, and close

files on the server• PHP can collect form data• PHP can send and receive cookies• PHP can add, delete, modify data in your database• PHP can restrict users to access some pages on your

website• PHP can encrypt data

Page 4: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Why PHP?• PHP runs on various platforms (Windows, Linux,

Unix, Mac OS X, etc.)• PHP is compatible with almost all servers used today

(Apache, IIS, etc.)• PHP supports a wide range of databases• PHP is free. Download it from the official PHP

resource: www.php.net• PHP is easy to learn and runs efficiently on the

server side

Page 5: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Basic PHP Syntax• A PHP script can be placed anywhere in the document.

• A PHP script starts with <?php and ends with ?>:

• <?php// PHP code goes here?>

• PHP Case Sensitivity

• In PHP, all user-defined functions, classes, and keywords (e.g. if, else, while, echo, etc.) are NOT case-sensitive.

• However; in PHP, all variables are case-sensitive.

• Ex.

Page 6: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Variables• As with algebra, PHP variables can be used to hold values (x=5) or

expressions (z=x+y).• A variable can have a short name (like x and y) or a more descriptive

name (age, carname, total_volume).• Rules for PHP variables:• A variable starts with the $ sign, followed by the name of the variable• A variable name must start with a letter or the underscore character• A variable name cannot start with a number• A variable name can only contain alpha-numeric characters and

underscores (A-z, 0-9, and _ )• Variable names are case sensitive ($y and $Y are two different

variables)

Variables are "containers" for storing information:• <?php

$x=5;$y=6;$z=$x+$y;echo $z;?>

Page 7: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Variables Scope• In PHP, variables can be

declared anywhere in the script.• The scope of a variable is the

part of the script where the variable can be referenced/used.

• PHP has three different variable scopes:

• local• global• static

Page 8: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP echo and print Statements• There are some differences

between echo and print:• echo - can output one or

more strings• print - can only output one

string, and returns always 1• echo and print are a

language construct, and can be used with or without parentheses: echo or echo().

Page 9: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Data Types• PHP Strings• A string is a sequence of characters, like "Hello

world!".• PHP Integers• An integer is a number without decimals. Rules for

integers:– An integer must have at least one digit (0-9)– An integer cannot contain comma or blanks– An integer must not have a decimal point– An integer can be either positive or negative– Integers can be specified in three formats: decimal (10-

based), hexadecimal (16-based - prefixed with 0x) or octal (8-based - prefixed with 0).

• PHP Floating Point Numbers• A floating point number is a number with a decimal

point or a number in exponential form.• PHP Booleans• Booleans can be either TRUE or FALSE.• PHP Arrays• An array stores multiple values in one single

variable.

Page 10: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP String Functions• The PHP strlen() function: echo strlen("Hello

world!");• The PHP strpos() function: echo strpos("Hello

world!","world");• Complete PHP String Reference: library

http://www.w3schools.com/php/php_ref_string.asp.• Different between • Echo “ “ & echo ‘ ‘;

Page 11: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP if...else...elseif Statements• In PHP we have the following

conditional statements:• if statement - executes some code

only if a specified condition is true• if...else statement - executes some

code if a condition is true and another code if the condition is false

• if...elseif....else statement - selects one of several blocks of code to be executed

• switch statement - selects one of many blocks of code to be executed

Page 12: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Loops• In PHP, we have the following

looping statements:

• while - loops through a block of code as long as the specified condition is true

• do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true

• for - loops through a block of code a specified number of times

• foreach - loops through a block of code for each element in an array

Page 13: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

While Loops

while (condition) {

// Do something.

}

Page 14: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

For Loops

for (initial expression; condition; closing expression) {

// Do something.

}

for ($i = 1; $i <= 10; $i++) {

echo $i;

}

Page 15: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Arrays• In PHP, the array() function is used to

create an array:• In PHP, there are three types of arrays:

– Indexed arrays - Arrays with numeric index– Associative arrays - Arrays with named keys– Multidimensional arrays - Arrays containing

one or more arrays.– Complete PHP Array Reference

http://www.w3schools.com/php/php_ref_array.asp

Page 16: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Creating Arrays

$band[] = 'Jemaine';

$band[] = 'Bret';

$band[] = 'Murray';

$band['fan'] = 'Mel';

$band['fan'] = 'Dave'; // New value

$fruit[2] = 'apple';

$fruit[2] = 'orange'; // New value

$states = array (

'IA' => 'Iowa',

'MD' => 'Maryland'

);

$artists = array ('Clem Snide', 'Shins', 'Eels');

Page 17: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Looping Through Arrays

foreach ($array as $value) {

// Do something with $value.

}

// Or:

foreach ($array as $key => $value) {

echo "The value at $key is $value.";

}

Page 18: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Sorting Arrays

• sort() - sort arrays in ascending order• rsort() - sort arrays in descending order• asort() - sort associative arrays in

ascending order, according to the value• ksort() - sort associative arrays in

ascending order, according to the key• arsort() - sort associative arrays in

descending order, according to the value

• krsort() - sort associative arrays in descending order, according to the key

Page 19: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Arrays and Strings

$array = explode (separator, $string);

$string = implode (glue, $array);

$s1 = 'Mon-Tue-Wed-Thu-Fri';

$days_array = explode ('-', $s1);

// $days_array now a five-element array, with Mon indexed at 0.

$s2 = implode (', ', $days_array);

// $s2 now a comma-separated list of days: Mon, Tue, Wed, Thu, Fri.

Page 20: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Global Variables - Supergloba

• The PHP superglobal variables are:

• $GLOBALS• $_SERVER• $_REQUEST• $_POST• $_GET• $_FILES• $_ENV• $_COOKIE• $_SESSION

Page 21: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Client/Server Environment Variables• Environment variables

– Provide information about execution environment• Type of Web browser

• Type of server

• Details of HTTP connection

– Stored as array in PHP• $_ENV

Variable name Description $_SERVER Data about the currently running server. $_ENV Data about the client’s environment. $_GET Data posted to the server by the get method. $_POST Data posted to the server by the post method. $_COOKIE Data contained in cookies on the client’s computer. $GLOBALS Array containing all global variables. Fig. 26.11 Some useful global arrays.

Page 22: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

An HTML Form<form action="handle_form.php" method="post">

<p><label>Name: <input type="text" name="name" size="20" maxlength="40" /></label></p>

<p><label>Email Address: <input type="text" name="email" size="40" maxlength="60" /></label></p>

<p><label for="gender">Gender: </label><input type="radio" name="gender" value="M" /> Male <input type="radio" name="gender" value="F" /> Female</p>

<p><label>Age:

<select name="age">

<option value="0-29">Under 30</option>

<option value="30-60">Between 30 and 60</option>

<option value="60+">Over 60</option>

</select></label></p>

<p><label>Comments: <textarea name="comments" rows="3" cols="40"></textarea></label></p>

<p align="center"><input type="submit" name="submit" value="Submit My Information" /></p>

</form>

Page 23: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PhP Form Handling

• Form processing– action property

• Where to send form data (In/Out)

– method property• The PHP superglobals $_GET and $_POST are used to collect

form-data.

• Each element has unique name

Page 24: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Choosing a Method

GET

• The standard method for all server requests

• Data appended to the URL

• Can be bookmarked• User can click Back• Used for requesting

information

POST

• Data is not visible in the URL

• Much larger limit on the amount of data that can be submitted

• Can send files• Users see warnings if

they click Back• Used for requesting

action

Page 25: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Handling a Form

• Use $_REQUEST['name']• Or use $_GET['name'] and $_POST['name'],

depending upon the form’s method value• Always load the form through a URL!

Page 26: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Handling a Form

<?php # Script 2.2 - handle_form.php

// Create a shorthand for the form data:

$name = $_REQUEST['name'];

$email = $_REQUEST['email'];

$comments = $_REQUEST['comments'];

// Print the submitted information:

echo "<p>Thank you, <b>$name</b>, for the following comments:<br />

<tt>$comments</tt></p>

<p>We will reply to you at <i>$email</i>.</p>\n”;

?>

Page 27: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Form Handling• GET vs. POST

– Both GET and POST create an array (e.g. array( key => value, key2 => value2, key3 => value3, ...)).

– This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.

– Both GET and POST are treated as $_GET and $_POST.– These are superglobals, which means that they are always

accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.

– $_GET is an array of variables passed to the current script via the URL parameters.

– $_POST is an array of variables passed to the current script via the HTTP POST method

Page 28: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Form Handling• When use GET

– Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL).

– GET also has limits on the amount of information to send (2000 characters).

– GET may be used for sending non-sensitive data.

• When use POST– Information sent from a form with the POST method is

invisible to others (all names/values are embedded within the body of the HTTP request).

– has no limits on the amount of information to send.– Developers prefer POST for sending form data.

Page 29: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

• Example PHP Form Handling

Page 30: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Form ValidationProper validation of form data is important to protect your form from hackers and spammers. Check the input data weather user appropriate data or not.

•$_SERVER["PHP_SELF"]

– The $_SERVER["PHP_SELF"] is a super global variable that returns the filename of the currently executing script.

– $_SERVER["PHP_SELF"] sends the submitted form data to the page itself, instead of jumping to a different page.

•The htmlspecialchars()– The htmlspecialchars() function converts special characters to HTML

entities. This means that it will replace HTML characters like < and > with &lt; and &gt;.

– This prevents attackers from exploiting the code by injecting HTML or Javascript code (Cross-site Scripting attacks) in forms.

•Big Note on PHP Form Security– The $_SERVER["PHP_SELF"] variable can be used by hackers!

– If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.

Page 31: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Form Validation

How To Avoid $_SERVER["PHP_SELF"] Exploits? • $_SERVER["PHP_SELF"] exploits can be avoided by using the htmlspecialchars()

function.• <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?

>">

•Validate Form Data With PHP The first thing we will do is to pass all variables through PHP's

htmlspecialchars() function. Strip unnecessary characters (extra space, tab, newline) from the user input

data (with the PHP trim() function) Remove backslashes (\) from the user input data (with the PHP stripslashes()

function)

The next step is to create a function that will do all the checking for us.

Page 32: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Validating Form Data

• Never trust external data!• Use isset() to confirm variable has a value• Use !empty() to confirm variable has a non-empty

value• Check the data’s type, when appropriate, for

example, using is_numeric()• Check the data’s value, when appropriate.

Page 33: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Form ValidationExample: <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Page 34: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

PHP Forms - Required Fields

Page 35: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Common Problems

• Failure to load the form through a URL• Incorrect reference to the PHP script (e.g., location or

name)• Case-sensitivity issue with PHP variables• Incorrect element names in the HTML form

Page 36: LEARN THE QUICK AND EASY WAY! VISUAL QUICKPRO GUIDE Chapter 2: Programming with PHP Copyright © 2012 by Larry Ullman Dr. Mogeeb Mosleh Saturday (9.00-11.00pm)

LEARN THE QUICK AND EASY WAY!

VISUAL QUICKPRO GUIDE

Superglobal Arrays

• $_GET• $_POST• $_REQUEST• $_SERVER• $_ENV• $_SESSION• $_COOKIE