+ All Categories
Home > Documents > Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS...

Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS...

Date post: 19-Dec-2015
Category:
Upload: jemima-thornton
View: 239 times
Download: 2 times
Share this document with a friend
101
Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP is used for server-side programming
Transcript
Page 1: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Introduction to PHPPersonal Home Page original name – now called:PHP: Hypertext Preprocessor

CS 268

These slides have been adapted from CS319 where PHP is used for server-side programming

Page 2: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Web TechnologiesWeb Programming

Technologies

Server-sideprocessing

Client-sideprocessing

Compiledprograms

Server-side scripts

CGI programs

Java Servlets Active Server Pages ASP

Java Server Pages JSP

Compiled programs on client workstation

Java applets

Java Web Start

Client-sidescripts

JavaScript

VBScript

ASP.NET

PHP Hypertext Preprocessor PHP

AJAX

Java Server Faces JSF

Microsoft ClickOnce

ColdFusion CF

Page 3: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Web TimelineTCP/IP (1970s)

HTTP

CGI

ColdFusionJavaScriptApplets

ASPFlash

PHP

ServletsJSP

Java Web StartASP.NET

Java Server FacesMSClickOnceAjax

HTML

Cascading Stye Sheets

Apache Web Server

IIS Web Server (Microsoft's Web Server)

Apache-Tomcat Web Server

1990 1995 2000 2005

XML

Page 4: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

ASP and CF Example

Page 5: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

ASP (Active Server Page) Code

Page 6: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Comparable Cold Fusion Code

Page 7: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

JSP (Java Server Page) Example

Page 8: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

JSP Example - Code

Page 9: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP Example (code shown in next slide)

Page 10: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.
Page 11: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

So why use PHP? PHP uses a similar coding style to ASP, JSP, and Cold Fusion. With a PHP, you can first create a static Web page, then add the

commands for dynamic processing (same as ASP, JSP, Cold Fusion) PHP – the most? widely used server-side technology There are ways to convert PHP to C++ and compile it to native binaries

Facebook is doing this with HipHop (they developed it and open sourced it)

Page 12: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

So what about other technolgies? Java Server Faces, ASP.NET, etc??

These are harder to learn than JSP, PHP, ASP or ColdFusion. They are compiled once making them faster running They minimize mixing HTML markup with Server-side code –

which can sometimes be a big advantage

You will use some of these more complex technologies this semester.

Page 13: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP Development Environment Minimum needed (all free):

Apache web server PHP add on

Apache doesn't know anything about PHP unless you add its .so file to its modules folder and add appropriate entries to httpd.conf

MySQL Easiest way to get and install

Google - "XAMPP" http://www.apachefriends.org/en/xampp-windows.html To test pages from a local XAMPP installation:

Save them in the default XAMPP Apache folder:

C:\xampp\apache\htdocs Run them like this:

http://localhost/yourPagename.php

Page 14: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Infinite Loop affect on Web Server An infinite loop will run forever unless something outside of it stops it. $count isn't incremented in the

following example so the loop won't stop on its own:

PHP.ini sets number of seconds a script is allowed to run Default is in seconds: max_input_time = 60

Can reset to whatever amount of time for a particular PHP page – either shorter or longer:

While running, loop slows down the server!

Page 15: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Class’s (CS268) PHP Environment DreamWeaver - IDE for creating:

HTML, CSS, JavaScript, PHP, and more

http://yoda.cs.uwec.edu/CS268/students Entire class PHP development web server If “anyone” crashes the server – we all suffer!

Page 16: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Class’s (CS268) PHP Environment Process:

Map a drive to \\yoda.cs.uwec.edu\CS268$ Don’t forget the $ after CS268$– it doesn’t matter if the drive letter is X or any other letter

Create pages using DreamWeaver in your Yoda folder Test pages using this sort of URL:

http://yoda.cs.uwec.edu/CS268/students/yourFolder/PageFolder/PageName.php

Windows Explorerpress Alt key to see top menu

If using your own computer (not a lab computer) you need to make a VPN before mapping a drive.And then check the box: Connect using diff... And use UWEC\username to change the domain

Page 17: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Decent Free PHP Editors The following provide color coding for html,

JavaScript and PHP None of the following have useful code completion:

Notepad++ PHPad PHPCoder Subline text

Page 18: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Basic Syntax A PHP file normally contains HTML tags – just like an

ordinary HTML file (and possibly JavaScript) – along with additional PHP scripting code

Simple Hello World example:

Page 19: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Basic Syntax echo

PHP command sending text back to the browser Shorthand if enabled on web server

Everything between <?= and ?> is sent back to browser as text:

But – use echo instead (previous slide) You can’t be sure all servers have this enabled.

Page 20: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Using Variables Variable names start with $ Like JavaScript they can hold “any” data type Data types include:

Booleans, Integers, Floats, Strings, Arrays, Objects

PHP will make conversions as needed to data types Which, like JavaScript may not be what you want

Page 21: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Generating an HTML Table Data retrieved from a database or file is often displayed in an HTML table.  To keep this example simple, it generates a table containing the numbers

from 1 to 10 (and doesn’t retrieve data from a database table – I'll show how to do that later)

Page 22: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What will the following display?

A. num is: 5

B. num is:

C. 5

D. Nothing an error occurs

Page 23: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Answer - What will the following display?

A. num is: 5

B. num is:

C. 5

D. Nothing an error occurs

+ isn't overloaded in PHP – it MUST do addition (not catenation)The string "num is: " is converted to zero to allow the additionNo error is generated

Page 24: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

String concatenation Operator A single period . is the concatenation

operator

Page 25: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Improving PHP Error Reporting Add this as the first line in a PHP page:

This will catch errors of this type

$_REQUEST["c_type"] should be ["cust_type"] And $c_type should be $cust_type Without the error_reporting(E_ALL) code no errors are displayed (until later

when something else fails). With it:

Page 26: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Formatting Currency Use PHP’s number_format function

number_format(number,decimals,decimalpoint,separator)

Example:

Result: Notice the dollar sign $ comes from here,not from the number_format function

Page 27: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Referencing Form Values in PHPs

Syntax to reference a form parameter from a PHP:

Example:

Important – The name you give to a form’s input in the previous page, for example: <input type=text name=Lastname> is what you use for form_parameter_name in $_REQUEST.

<?php $Lastname = $_REQUEST["Lastname“]; ?>

$_REQUEST["form_parameter_name“]

Note: $_REQUEST works for method=“get” and method=“post”More specific syntax only working for one or the other is:$_GET and $_POST

Notice – square brackets not parentheses

Page 28: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What will the following code display?Assume previous page passes a parameter named qty with value 3

A. 2

B. 223

C. 8

Page 29: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Answer - What will the following code display?Assume previous page passes a parameter named qty with value 3

Answer is A. 2 $_REQUEST[“quantity”] should be [“qty”] PHP doesn’t display an error – it just converts $quantity to zero – 0

and does the multiplication: $price * $quantity Make this the first line in your file and PHP will display an error:

<?php error_reporting(E_ALL); ?>

What does $quantity contain? An empty string: "" ?? A zero: 0 ??

Page 30: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Proof that $quantity == "" (remember the parameter was named qty, not quantity)

Page 31: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

But wait! Proof that $quantity == 0 (remember the parameter was named qty, not quantity)

Page 32: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What is $quantity really??Remember the parameter passed to the page is named qty, not quantity

$quantity is NULL -- but PHP willconvert it to a 0 or "" if youuse it in an expression or operation

Page 33: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What will the following code display?Assume previous page passes a parameter named qty with value 3

A. quantity is empty string

B. quantity is: 3

C. quantity is:

Page 34: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Answer - What will the following code display?Assume previous page passes a parameter named qty with value 3

Answer is: C. quantity is: In the if, $quantity is assigned ""

= is the assignment operator, not the comparison operator!

Note: always remember to use == for comparisons! Then you don't have to remember the stuff in this slide's note

Page 35: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Select Lists This list is generated from a database query

categoryid is passed to the php page as an HTML form parameter

The form is submitted by an input of type submit.

Page 36: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Select Lists

<td><select name=categoryid size=4>

<?php foreach($stmt as $row) { ?>

<option value=<?php echo $row["categoryid"] ?>>

<?php echo $row["categorydescription"] ?>

</option>

<?php } ?>

</select>

</td>

What this generates (look in view/source):

<select name=categoryid size=4>

<option value=3>All Terrain Vehicles</option>and so on…

Page 37: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Code generating a radio list<?php foreach($stmt as $row) { ?>

<tr>

<td>

<input type="radio" name="categories" value="<?php echo $row["categoryid"]; ?>">

<?php echo $row["categorydescription"]; ?>

</td>

</tr>

<?php } ?>

What this generates (look in view/source):

<input type="radio" name="categories" value="3">All Terrain Vehicles

<input type="radio" name="categories" value="1">Appareland so on…

Page 38: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Generating a URL parameter list<?php foreach($stmt as $row) {

<tr><td><a href=displayCategories.php?categoryid=<?php echo $row["categoryid"]; ?>>

<?php echo $row["categorydescription"]; ?></a></td></tr>

<?php } ?>

You don't need <form…> </form> tags in urlSportMotors.php. You are using <a href…> to directly call the next php page.

Notice how ? followed by the parameter name and an equal sign, followed by the value is concatenated into the hyperlink

What this generates (source view):<tr><td><a href=displayCategories.php?categoryid=3>All Terrain Vehicles</a></td></tr>

<tr><td><a href=displayCategories.php?categoryid=1>Apparel</a></td></tr>

Page 39: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What is a Cookie? Data saved on the client workstation

Stored as a text file or temporarily in main memory Can read or modify a cookie only from Web programs on

the same Web server that originally created it If reading and writing cookies using JavaScript the script can

read and right cookies created by JavaScript on 'your' computer (can't read cookies created from other web sites)

Cookie types: Temporary: only lasts during the current browser session (close

the browser and they are gone) Persistent: stores data in the client file system that is available

across multiple browser sessions (close the browser, come back the next day, and the cookie is still there)

Page 40: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Cookies Data you might want to store across browser sessions and/or retain as

a user browses from one page to the next: Username/password Shipping address Credit card number Browsing preferences/keywords Shopping cart items

How can you store user data? Store it on a remote server (the Web server, a database server, etc.) Store it in a cookie on the client workstation

Why do you think storing it on the client workstation might be preferred? Temporary Cookie exists only during a browser session

Starts when the user starts the browser Ends when the user closes the browser

Persistent Cookie saved as a file Doesn't necessarily stay there forever...

Page 41: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Internet Explorer Cookies Microsoft Internet Explorer complies with the following

recommended minimum limitations: 10 kilobytes per cookie for IE8 (previously was 4096 bytes) at least 20 cookies per unique host or domain name

If a server in the domain sends more than 20 cookies to a client computer, the browser on the client computer automatically discards some old cookies.

2007: This limit was increased to simplify the development and the hosting of Web applications on domains that use many cookies. Increased the number of cookies that Internet Explorer can store for each domain from 20 to 50.

Page 42: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Current Cookie Limits Firefox Cookie Limits

150 cookies per unique host or domain name

Opera Cookie Limits 63 cookies per unique host or domain name

Chrome Cookie Limits 178 cookies per unique host or domain name

Safari Cookie Limits 188 cookies per unique host or domain name

Internet Explorer 50 cookies per unique host or domain name

Page 43: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Problems With Cookies Not supported by all browsers Some people disable cookies

Tools -> Internet Options -> Privacy tab

However, many commercial Web sites create/use cookies!

Page 44: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Cookie Data Usually structured as name=value pairsvariable_name=variable_value

List is delimited by semi-colons ExampleuserID=stevende;userPIN=1234;

Page 45: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating a Temporary Cookie using JavaScript Use the cookie property of the document object Assign to it a text string that stores both the

name and value pair (with an equal sign between them)

Example:

<script> document.cookie = "userID=smithjp";</script>

Page 46: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Referencing the Contents of a Cookie To reference the contents of a cookie,

reference the document.cookie property Example:

alert("Cookie value is " + document.cookie);

Page 47: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating a Temporary Cookie (continued) All of the cookie data for a browser session is

referenced by document.cookie To add another name/value pair to an

existing cookie, use the following syntax:

document.cookie = "PIN=" + document.frmLogin.txtPIN.value;document.cookie = “UserID=" + document.frmLogin.txtUserID.value;

Page 48: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating Persistent Cookies To create a persistent cookie:

create a temporary cookie and

add an expiration date format: expires=Day, DD-Mon-YYYY HH:MM:SS GMT you must add the "expires" to each name/value pair

For example if the userid is smithjp this will concatenate to:

Note: you could directly enter the cookie and value without calling document.frmLogin.txtUserID.value if you always wanted the same value used (smithjp for example)

document.cookie = "userID="+ document.frmLogin.txtUserID.value + ";expires=Wednesday, 02-Mar-2020 12:00:00 GMT;";

document.cookie = "userID=smithjp;expires=Wednesday, 02-Mar-2020 12:00:00 GMT;";

Page 49: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating a Temporary Cookie using PHP

Use the setcookie function Pass it the cookie name and value Example:

<?php setcookie("userID", "smithjp"); ?>

Page 50: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Referencing the Contents of a Cookie JavaScript:

Caution: document.cookie returns "all" cookies for the current host

PHP:

$_COOKIE["name"] returns a single specified cookie

alert("Cookie value is " + document.cookie);

<?php echo $_COOKIE["userID"]; ?>

Page 51: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Temporary Cookie (continued) To add another name/value pair to an existing

cookie using JavaScript, use the following sort of syntax:

Using PHP:

Assumes txtPIN and txtUserID sent from previous page

<script type="text/javascript"> document.cookie = "PIN=" + document.frmLogin.txtPIN.value; document.cookie = "UserID=" + document.frmLogin.txtUserID.value;</script>

<?php setcookie("PIN", $_REQUEST["txtPIN"]); ?><?php setcookie("UserID", $_REQUEST["txtUserID"]); ?>

Assumes you want to save a user entry

Page 52: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating Persistent Cookies - PHP Add an expiration date parameter

This is in seconds elapsed since: January 1 1970 00:00:00 GMT

PHP time() function returns current number of seconds since 1/1/1970

To set cookie to expire in one year from current time:60 sec * 60 min * 24 hours * 365 days * time()

For example:

If you always want the same value assigned:

<?php setcookie( "UserID", $_REQUEST["txtUserID"], 60*60*24*365 + time() ); ?>

<?php setcookie( "UserID", "smithjp", 60*60*24*365 + time() ); ?>

Page 53: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Retrieving and Setting Preferences with Cookies In all pages with preferences add:

Within the body tag: onload="getPreferences();" In JavaScript getPreferences() function (which you write):

Call another function for each preference:getBgColor();getFontColor();etc.

In getBgColor (etc.) function: Retrieve cookie value If found, set page appearance according to preference

- Here's the first use for tag id attributes this semester! - Use document.getElementByID("idname") to set values var mainTable = document.getElementById("mainTable"); mainTable.border = borderWidth;

If not, use default values

Assumes:<table id="mainTable" …is in the page

Page 54: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Retrieving and Setting Preferences with Cookies In pages

Assumes:<table id="mainTable" …is in the page

The body tag doesn'tneed an id assigned toit. document.body is abuilt in way to access it.

getCookie function must be copied into the page

Page 55: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Retrieving Preferences in a PHP Page In .php pages

Use the $_COOKIE array to retrieve cookie values Use javascript in the .htm page to create preference cookies

or - you could alternatively use server-side PHP code to create cookies

Page 56: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Storing Preferences with Cookies In page allowing user to set preferences:

Add onchange="setWhatever()" to appropriate inputs Or add a button to click and set the preferences

In setWhatever functions: Change the appearance to the user's selection Save user selection in a persistent cookie

Show the change tothe user immediately

Save the cookie forfuture page accesses

Page 57: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Storing Preferences Example

Page 58: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Alternatives? Everything done using JavaScript could be done

instead using server-side PHP code But – all the pages would need to be PHP pages!

And it will take longer to show a user's preference changes to them as they make the changes It would require calling a server PHP page to in turn send back a

request to the browser to save the cookie and update the page appearance

Best practice? Have the user change the preferences using JavaScript On page access read and set them using PHP

Page 59: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Topics

Session Variables

PHP include command

Page 60: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating a session Before storing or retrieving session variables

Start a session with this php code at the top of every page using session variables – it must be before any html or text is sent

Registers the user's session with the server If this is the first page requested by this browser from

the server Assigns a UID (unique identification number) for the user's

session

Page 61: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Session Variable Commands To create a session variable:

To read a session variable:

To remove

To test for existence (assumes already attempted to read the session variable into $name)

Page 62: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Storing Compound Data in Value Sometimes you need to store several pieces of data

within a single session variable A delimited string can be used to store compound data

Session variable's value will be a delimited string If you want the value to store two (or more) pieces of data

concatenate them into a single string with a delimiter between them Delimiters can be any valid character or symbol that won't otherwise occur in

the data. Examples might be a colon :, period ., semi-colon ; etc. Example storing product id (23), quantity (1), and price (125.99) for an item:

23:1:125.99 And a session variable named "item1" might have the value "23:1:125.99" as its

value

Page 63: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

User Interface to Compound data(catalog items retrieved from database query) Need a pick list of some sort

select, radio, hyperlinks, etc.

When user selects an item Send the user's selection to a php page that adds it to their cart

(and the cart is stored using session variables) The selection might have several pieces of information that

should be included The item's id Description Price Quantity etc?

Page 64: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Use delimited string to store several items in a single value attribute

User Interface to Compound data(catalog items retrieved from database query)

Page 65: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Code generating previous page's values from a loop retrieving database data:

User Interface to Compound data(catalog items retrieved from database query)

Page 66: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Storing User's Selection in Session Variable Catalog form submits user's choice to PHP page

In the PHP page, retrieve choice using $_REQUEST PHP's list and explode functions separate the delimited items

explode(separator, string, limit) // limit optional breaks the string into an array uses the separator to determine where to split the string if limit is omitted it will return all delimited items if limit is included it will only return the number specified

list(var1, var2, …) // at least one var is required assigns array values to a list of variables in one operation For example – assume the item parameter passed to this page contains "CB03:Bike:299.99":

Page 67: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP Adding to Cart If the name used for the session variable starts with a

number add an underscore to it – session variable names cannot start with a number (causes an error if you start a session variable name with a number)

Page 68: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP Adding to Cart (continued from previous slide)

What the previous session variables might look like using a colon : for the delimiter

"trampoline:499.95:1" $_SESSION["_342"] = "trampoline:499.94:1";

"drill:110.95:1" $_SESSION["_1928"] = "drill:110.95:1";

"drill bit:9.95:3" $_SESSION["_2937"] = "drill bit:9.95:5";

Session variable's name

Store other values as delimited stringShouldn't start a session variablename with a number – so addan underscore in front of them

Page 69: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Retrieving all Session Variables It can be useful to retrieve all session variables

For a shopping cart? You can make a session variable for each item in the cart.

$_SESSION is an array The index to the array is a string, however, not a number

This is called an "associative" array Typically implemented using a hash table All PHP arrays are associative arrays (even if you use a numeric index)

A foreach loop can be used to retrieve array items php's foreach works with all php arrays foreach($_SESSION as $name => $value) { … } $name (any valid variable name can be used) is assigned the current array element's index – for

$_SESSION this is the session variable's name $value (any valid variable name can be used) is assigned the current array element's value each

time the loop is processed

Page 70: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Array Example

Page 71: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Retrieving all Session Variables

Page 72: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Displaying Shopping Cart Items Use foreach loop (as in previous slide) Use PHP's list and explode functions to separate the delimited items in each

stored value

Page 73: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Important "Gotcha" to watch out for! What if you store non-shopping cart items as session

variables as well as shopping cart items? For example after logging in it is common to use a session variable to indicate the user is logged in as they go from one page to another. You need a way to ignore the non-cart session variables when

you loop through all the session variables Easy way is to always add an underscore in front of the cart

variable names - don't add it to any other session variables used in the site pages Then when loop through the session variables only process the ones

beginning with an underscore!

Page 74: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Selecting session variables with underscores substr function

string substr ( string $string , int $start [, int $length ] )

Alternative for reading first char in a string: if($partnumber[0] == "_") {

Use array indexing for desired char in the string Easier and faster than the substr approach

Page 75: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Revised code to display the cart

Page 76: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP Include Command PHP include command allows inserting contents of a file within the

current file

Use whenever you find yourself writing the same html or php code over an over again in many pages Put the common code in a separate file and include it in all the pages

needing it. For example: To add a common navigation menu to all the pages on your site To add code connecting to a database To add code verifying a user is logged in prior to allowing to secure pages

Has to be in a PHP page (.php extension) to allow the php include command to be processed sometimes you will use a PHP page when the only PHP commands in the page

are include commands

Page 77: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Logging In

Page 78: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Basic Idea HTML Form (in either htm or php page)

collects username and password Sends them to PHP page validating the login

PHP page queries database for username and password If found, stores their userid (customerid, or whatever is the

primary key identifying them) in a session variable and displays the next page

If not found, returns them to the initial login page with an appropriate message

Page 79: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

New Concepts Command to forward the user to a different page

Preventing a user from directly accessing a page that requires a login

SQL Injection (if you haven't taken CS260)

Page 80: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Sessions A session is associated with a visitor to a Web site Data can be put in the session and retrieved from it A different set of data is kept for each visitor to the site

If you bring up two different browsers or run two browsers from two different machines, these will be assigned to different server sessions.

Sessions work by creating a unique identification(UID) number for each visitor and storing variables based on this ID. This helps to prevent two users' data from getting confused with one another when visiting the same webpage.

Page 81: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Creating a session Before storing or retrieving session variables

Start a session with this php code at the top of

every page using session variables – it must be before any html or text is sent

Registers the user's session with the server Assigns a UID (unique identification number) for

the user's session if this is the first page requested by this browser from the server

Page 82: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Session Issues

If you go to lunch before submitting your order, what happens to your shopping cart items?

How much memory will a busy Web server need for storing session variables?

Do Session variables eliminate the need for cookies? session tracking creates a cookie to store a session identifier for a visitor

Page 83: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Sessions When a user leaves the Web site and doesn’t

return? What happens to session variables? After 24 minutes with no activity from the user

The server discards the variables stored for the user (otherwise the server’s memory would eventually be filled up

with no longer needed session variables)

Page 84: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP command redirecting to a different page header("Location:Login.php"); What does this command really do?

From the Web server’s PHP page to the browser: Sends a request to the user’s browser asking the user’s browser to in turn

send back a request for the specified page From the browser to the Web server:

Receives the request from the server and sends back to the Web server a request for the specified page

And from the Web server to the browser: Sends back the newly requested page

Must be placed before any html or text is sent to the browser

Page 85: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Login Session Variable Create a session variable if a user successfully logs in Variable is then checked by other pages requiring login

All of these pages redirect to the login page if this variable isn’t found

Why use a session variable? Con

times out in 24 minutes uses server memory

Pro can’t be seen or read on the client computer times out in 24 minutes

Page 86: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Session Variable Commands To create a session variable:

To read a session variable:

To remove

To test for existence (assumes already attempted to read the session variable into $name)

Page 87: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Logging in - Putting it togetherI'm not showing code creating the query from thef_userid and f_pin inputs sent from the login pageand attempting to retrieve based on these from the database

PDO wayto retrievea single rowof data

Page 88: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Preventing a user from directly accessing a page that requires a login

Test for the existence of the session variable Put this code at the top of pages that shouldn't be accessed

unless the user has logged in successfully

Page 89: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Review the code. Even ifusername and password are found, the user will be redirected tologin.php. Why?

menu.php

processLogin.php

A. The session variable loggedin is misspelledB. is_null($loggedin) should be empty($loggedin)C. session_start(); should be at the top of menu.phpD. Logic error in processLogin – should be checking == false for username and

password

Page 90: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Moving login verification to separate file PHP include command allows inserting

contents of a file within the current file

Page 91: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Moving login verification to separate file And in the included file:

Reuse this for each page requiring a login

Page 92: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Preventing cached pages from being displayed A user adds a new entry then used the browsers

back button to view previous page showing all entries If page is cached.

The new entry isn't shown

Page 93: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Preventing cached pages from being displayed PHP default is to prevent php pages from being cached

Specified in the php.ini configuration file (and we don't have access to that file)

Can't assume this will always be the default behaviour PHP session_cache_limiter command

Get or set the current cache limiter For Leela: Displays:

Page 94: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

<?phpheader("Pragma: no-cache");

header("Cache-Control: no-store, no-cache, must-revalidate");

header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");

?>

Prevent cached pages from being displayed

Page 95: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Code at the top of each page requiring a login:<?php session_start();

header("Pragma: no-cache"); header(("Cache-Control: no-store, no-cache, must-revalidate");

header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");

$userid = $_SESSION["userid"];// wait until attempt to retrieve userid to turn this onerror_reporting(E_ALL);if(is_null($userid) == true) {

// they haven't logged in - send them back to the login pageheader("Location:Login.php");die();

} ?>

Preventing a page from being displayed without a login (place in a separate file and include it)

Page 96: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

What is a SQL Injection Attack? A form of attack on a database-driven Web site in which the attacker

executes unauthorized SQL commands Possible when a query is concatenated together from user inputs. SQL injection attacks are prevented through input validation.

Page 97: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Might not be a problem with PHP What are Magic Quotes?

When on, all ', ", \ and NULL characters are prepended with a backslash automatically. The php function addslashes() also does this

This feature has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 6.0.0. Relying on this feature is highly discouraged.

If on, SQL Injection isn't possible But – have to assume it isn't on if web site might be

moved to a different server

Page 98: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Might not be a problem with PHP Magic Quotes are ON for our class PHP server But have to assume it won't be there if you

deploy a PHP page (and it probably WON'T if working from a different server)

Page 99: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

Have to Assume Worst and Defend against SQL Injection! Use addslashes function to prepend slash to characters commonly used for SQL Injection:

This will cause the query looking up username and password to fail and deny the login if SQL Injection is tried. If Magic Quotes are on you wind up with two slashes in front of a single quote \\' Not a problem – you want the query to fail! OR – use a parameter query (search slideshow for:

PDO Parameter Query) This is what I recommend versus the addslashes approach

Page 100: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP and Object Oriented programming PHP supports OO I'm not going to cover this but you can learn

more here:http://www.phpfreaks.com/tutorial/oo-php-part-1-oop-in-full-effect

Page 101: Introduction to PHP Personal Home Page original name – now called: PHP: Hypertext Preprocessor CS 268 These slides have been adapted from CS319 where PHP.

PHP and MVC We will use Java to implement our MVC web

applications But – PHP can also use MVC I'm not going to cover this but to learn more

go to this URL:

http://php-html.net/tutorials/model-view-controller-in-php/


Recommended