Chapter 9. Managing State Information. Understanding State Information (continued) Understanding State Information 10/29/2011.

Similar documents
5/19/2015. Objectives. JavaScript, Sixth Edition. Saving State Information with Query Strings. Understanding State Information

CITS1231 Web Technologies. PHP s, Cookies and Session Control

WEB APPLICATION ENGINEERING II

Lecture 9a: Sessions and Cookies

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

How browsers talk to servers. What does this do?

CSE 154 LECTURE 13: SESSIONS

PHP State Maintenance (Cookies, Sessions, Hidden Inputs)

CSE 154 LECTURE 21: COOKIES

CSE 154 LECTURE 21: COOKIES

GET /index.php HTTP/1.1 Host: User- agent: Mozilla/4.0

Multimedia im Netz Online Multimedia Winter semester 2015/16. Tutorial 03 Minor Subject

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

Introduction. Server-side Techniques. Introduction. 2 modes in the PHP processor:

Lecture 7: Dates/Times & Sessions. CS 383 Web Development II Wednesday, February 14, 2018

Server-Side Web Programming: Python (Part 1) Copyright 2017 by Robert M. Dondero, Ph.D. Princeton University

PHP with data handling

CGI Architecture Diagram. Web browser takes response from web server and displays either the received file or error message.

Master Calendar Integrated Authentication Configuration Instructions. Dean Evans & Associates, Inc.

PHP: Cookies, Sessions, Databases. CS174. Chris Pollett. Sep 24, 2008.

Database Systems Fundamentals

Alpha College of Engineering and Technology. Question Bank

CSC309: Introduction to Web Programming. Lecture 8

COMP519 Web Programming Lecture 28: PHP (Part 4) Handouts

PHP INTERVIEW QUESTION-ANSWERS

DATABASE SYSTEMS. Introduction to web programming. Database Systems Course, 2016

CS105 Perl: Perl CGI. Nathan Clement 24 Feb 2014

How to work with cookies and sessions

home.php 1/1 lectures/6/src/ include.php 1/1 lectures/6/src/

Excerpts of Web Application Security focusing on Data Validation. adapted for F.I.S.T. 2004, Frankfurt

Form Processing in PHP

CHAPTER 2 MARKUP LANGUAGES: XHTML 1.0

CONTENTS IN DETAIL INTRODUCTION 1 THE FAQS OF LIFE THE SCRIPTS EVERY PHP PROGRAMMER WANTS (OR NEEDS) TO KNOW 1 2 CONFIGURING PHP 19

PIC 40A. Lecture 19: PHP Form handling, session variables and regular expressions. Copyright 2011 Jukka Virtanen UCLA 1 05/25/12

Lecture 6: More Arrays & HTML Forms. CS 383 Web Development II Monday, February 12, 2018

ITS331 IT Laboratory I: (Laboratory #11) Session Handling

Varargs Training & Software Development Centre Private Limited, Module: HTML5, CSS3 & JavaScript

SAS Report Viewer 8.2 Documentation

Part A Short Answer (50 marks)

LXXVIII. Session handling functions

Managing State. Chapter 13

Cookies and S essions 323

Chapter 10 Web-based Information Systems

Web Application Development (WAD) V th Sem BBAITM(Unit-1) By: Binit Patel

Web Focused Programming With PHP

USQ/CSC2406 Web Publishing

Lab 4: Basic PHP Tutorial, Part 2

(Frequently Asked Questions)

Saving State on the WWW

UNIT-VI CREATING AND USING FORMS

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

HTML 5 Form Processing

Web Programming with PHP

SCRIPTING, DATABASES, SYSTEM ARCHITECTURE

Zend Zend Certified PHP Developer. Download Full Version :

ABOUT WEB TECHNOLOGY COURSE SCOPE:

Creating HTML files using Notepad

HOW INFORMATION PASSES BETWEEN ONE SITES PAGES

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Server-side computing

Lecture 9 Server Browser Interactions

B. V. Patel Institute of BMC & IT 2014

CNIT 129S: Securing Web Applications. Ch 3: Web Application Technologies

CN Assignment I. 1. With an example explain how cookies are used in e-commerce application to improve the performance.

WEB SECURITY WORKSHOP TEXSAW Presented by Solomon Boyd and Jiayang Wang

Produced by. Web Development. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

University of Washington, CSE 154 Homework Assignment 7: To-Do List

ASP.NET State Management Techniques

A QUICK GUIDE TO PROGRAMMING FOR THE WEB. ssh (then type your UBIT password when prompted)

Web Programming Paper Solution (Chapter wise)

Mastering phpmyadmiri 3.4 for

zend. Number: Passing Score: 800 Time Limit: 120 min.

Autopopulation; Session & Cookies

Lecture 6 Session Control and User Authentication. INLS 760 Web Databases Spring 2013 Rob Capra

exam. Number: Passing Score: 800 Time Limit: 120 min File Version: Zend Certified Engineer

CPET 499/ITC 250 Web Systems. Topics

Web Programming 4) PHP and the Web

Enter Grade Report. No Place Like Gilbert Duenas. California State University San Marcos. Johnny Koons. CS 441 Software Engineering

PHP 5 if...else...elseif Statements

Web basics: HTTP cookies

The CartIt Commerce System Installation Guide

Hypertext Transport Protocol

Executing Simple Queries

CERTIFICATE IN WEB PROGRAMMING

This is CS50. Harvard College Fall Quiz 1 Answer Key

CSc 337 Final Examination December 13, 2013

What is PHP? [1] Figure 1 [1]

How is state managed in HTTP sessions. Web basics: HTTP cookies. Hidden fields (2) The principle. Disadvantage of this approach

P2_L12 Web Security Page 1

PHP Hypertext Preprocessor

CSCI-1680 WWW Rodrigo Fonseca

WIRIS quizzes web services Getting started with PHP and Java

User authentication, passwords

Subject Name: Advanced Web Programming Subject Code: (13MCA43) 1. what is PHP? Discuss different control statements

WEB SECURITY: WEB BACKGROUND

ColdFusion Application Security: The Next Step - Handout

last time: command injection

Lecture 11 & 12 PHP - III

Introductory workshop on PHP-MySQL

Information Security CS 526 Topic 8

Transcription:

Chapter 9 Managing State Information PHP Programming with MySQL 2 nd Edition Objectives In this chapter, you will: Learn about state information Use hidden form fields to save state information Use query strings to save state information Use cookies to save state information Use sessions to save state information 2 Information about individual visits to a Web site is called state information HTTP was originally designed to be stateless Web browsers store no persistent data about a visit to a Web site Maintaining state means to store persistent information about Web site visits with hidden form fields, query strings, cookies, and sessions Customize individual Web pages based on user preferences Temporarily store information for a user as a browser navigates within a multipart form Allow a user to create bookmarks for returning to specific locations within a Web site Provide shopping carts that store order information 3 4 1

Store user IDs and passwords Use counters to keep track of how many times a user has visited a site The four tools for maintaining state information with PHP are: Hidden form fields Query strings Cookies Sessions Figure 9-1 College Internship Available Opportunities Web site page flow 5 6 Figure 9-2 Registration/Log In Web page Figure 9-3 New Intern Registration Web page after successful registration 7 8 2

Figure 9-4 Verify Login Web Page for a successful login 9 Figure 9-5 The Available Opportunities Web page with the Intern information at top of screen 10 Using Hidden Form Fields to Save State Information Create hidden form fields with the <input> element Hidden form fields temporarily store data that needs to be sent to a server that a user does not need to see Examples include the result of a calculation The syntax for creating hidden form fields is: <input type="hidden"> Using Hidden Form Fields to Save State Information Hidden form field attributes are name and value When submitting a form to a PHP script, access the values submitted from the form with the $_GET[] and $_POST[] autoglobals To pass form values from one PHP script to another PHP script, store the values in hidden form fields 11 12 3

Using Hidden Form Fields to Save State Information echo "<form method='post' ". " action='availableopportunities.php'>\n"; echo "<input type='hidden' name='internid' ". " value='$internid'>\n"; echo "<input type='submit' name='submit' ". " value='view Available Opportunities'>\n"; echo "</form>\n"; Using Query Strings to Save State Information A query string is a set of name=value pairs appended to a target URL Consists of a single text string containing one or more pieces of information Add a question mark (?) immediately after the URL followed by the query string that contains the information you want to preserve in name/value pairs 13 14 Using Query Strings to Save State Information Separate individual name=value pairs within the query string using ampersands (&) A question mark (?) and a query string are automatically appended to the URL of a serverside script for any forms that are submitted with the GET method <a href="http://www.example.com/targetpage.php?firstname=don&lastname=gosselin& occupation=writer">link Text</a> Using Query Strings to Save State Information echo "{$_GET['firstName']} {$_GET['lastName']} is a {$_GET['occupation']}. "; Figure 9-6 Output of the contents of a query string 15 16 4

Using Cookies to Save State Information Query strings do not permanently maintain state information After a Web page that reads a query string closes, the query string is lost To store state information beyond the current Web page session, Netscape created cookies Cookies, or magic cookies, are small pieces of information about a user that are stored by a Web server in text files on the user s computer 17 Using Cookies to Save State Information Temporary cookies remain available only for the current browser session Persistent cookies remain available beyond the current browser session and are stored in a text file on a client computer Each individual server or domain can store between 20 and 70 cookies on a user s computer Total cookies per browser cannot exceed 300 The largest cookie size is 4 kilobytes 18 Creating Cookies The syntax for the setcookie() function is: setcookie(name [,value,expires, path, domain, secure]) You must pass each of the arguments in the order specified in the syntax To skip the value, path, and domain arguments, specify an empty string as the argument value To skip the expires and secure arguments, specify 0 as the argument value Creating Cookies Call the setcookie() function before sending the Web browser any output, including white space, HTML elements, or output from the echo() or print() statements Users can choose whether to accept cookies that a script attempts to write to their system A value of TRUE is returned even if a user rejects the cookie 19 20 5

Creating Cookies Cookies cannot include semicolons or other special characters, such as commas or spaces, that are transmitted between Web browsers and Web servers using HTTP Cookies can include special characters when created with PHP since encoding converts special characters in a text string to their corresponding hexadecimal ASCII value 21 The name and value Arguments Cookies created with only the name and value arguments of the setcookie() function are temporary cookies because they are available for only the current browser session <?php setcookie("firstname", "Don");?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>college Internships</title>... 22 The name and value Arguments The setcookie() function can be called multiple times to create additional cookies as long as the setcookie() statements come before any other output on a Web page setcookie("firstname", "Don"); setcookie("lastname", "Gosselin"); setcookie("occupation", "writer"); The name and value Arguments The following code creates an indexed cookie array named professional[] that contains three cookie values: setcookie("firstname", "Don"); setcookie("lastname", "Gosselin"); setcookie("occupation", "writer"); 23 24 6

The name and value Arguments The following code creates an associative cookie array named professional[] that contains three cookie values: setcookie("professional['firstname']", "Don"); setcookie("professional['lastname']", "Gosselin"); setcookie("professional['occupation']", "writer"); The expires Argument The expires argument determines how long a cookie can remain on a client system before it is deleted Cookies created without an expires argument are available for only the current browser session To specify a cookie s expiration time, use PHP s time() function setcookie("firstname", "Don", time()+3600); 25 26 The path Argument The domain Argument The path argument determines the availability of a cookie to other Web pages on a server Using the path argument allows cookies to be shared across a server A cookie is available to all Web pages in a specified path as well as all subdirectories in the specified path The domain argument is used for sharing cookies across multiple servers in the same domain Cookies cannot be shared outside of a domain setcookie("firstname", "Don, time()+3600, "/", ".gosselin.com"); setcookie("firstname", "Don", time()+3600, "/marketing/"); 27 28 7

The secure Argument Reading Cookies The secure argument indicates that a cookie can only be transmitted across a secure Internet connection using HTTPS or another security protocol To use this argument, assign a value of 1 (for TRUE) or 0 (for FALSE) as the last argument of the setcookie() function setcookie("firstname, "Don", time()+3600, "/", ".gosselin.com", 1); Cookies that are available to the current Web page are automatically assigned to the $_COOKIE autoglobal Access each cookie by using the cookie name as a key in the associative $_COOKIE[] array echo $_COOKIE['firstName']; Newly created cookies are not available until after the current Web page is reloaded 29 30 Reading Cookies Reading Cookies To ensure that a cookie is set before you attempt to use it, use the isset() function setcookie("firstname", "Don"); setcookie("lastname", "Gosselin"); setcookie("occupation", "writer"); if (isset($_cookie['firstname']) && isset($_cookie['lastname']) && isset($_cookie['occupation'])) echo "{$_COOKIE['firstName']} {$_COOKIE['lastName']} is a {$_COOKIE['occupation']}."; Use multidimensional array syntax to read each cookie value setcookie("professional[0]", "Don"); setcookie("professional[1]", "Gosselin"); setcookie("professional[2]", "writer"); if (isset($_cookie['professional'])) echo "{$_COOKIE['professional'][0]} {$_COOKIE['professional'][1]} is a {$_COOKIE['professional'][2]}."; 31 32 8

Deleting Cookies To delete a persistent cookie before the time assigned to the expires argument elapses, assign a new expiration value that is sometime in the past Do this by subtracting any number of seconds from the time() function setcookie("firstname", "", time()-3600); setcookie("lastname", "", time()-3600); setcookie("occupation", "", time()-3600); Using Sessions to Save State Information Spyware gathers user information from a local computer for marketing and advertising purposes without the user s knowledge A session refers to a period of activity when a PHP script stores state information on a Web server Sessions allow you to maintain state information even when clients disable cookies in their Web browsers 33 34 Starting a Session Starting a Session The session_start() function starts a new session or continues an existing one The session_start() function generates a unique session ID to identify the session A session ID is a random alphanumeric string that looks something like: 7f39d7dd020773f115d753c71290e11f The session_start() function creates a text file on the Web server that is the same name as the session ID, preceded by sess_ Session ID text files are stored in the Web server directory specified by the session.save_path directive in your php.ini configuration file The session_start() function does not accept any arguments, nor does it return a value that you can use in your script <?php session_start();... 35 36 9

Starting a Session You must call the session_start() function before you send the Web browser any output If a client s Web browser is configured to accept cookies, the session ID is assigned to a temporary cookie named PHPSESSID Pass the session ID as a query string or hidden form field to any Web pages that are called as part of the current session Starting a Session <?php session_start();...?> <p><a href='<?php echo "Occupation.php?PHPSESSID=". session_id()?>'>occupation</a></p> 37 38 Working with Session Variables Session state information is stored in the $_SESSION autoglobal When the session_start() function is called, PHP either initializes a new $_SESSION autoglobal or retrieves any variables for the current session (based on the session ID) into the $_SESSION autoglobal Working with Session Variables <?php session_start(); $_SESSION['firstName'] = "Don"; $_SESSION['lastName'] = "Gosselin"; $_SESSION['occupation'] = "writer";?> <p><a href='<?php echo "Occupation.php?". session_id()?>'>occupation</a></p> 39 40 10

Working with Session Variables Use the isset() function to ensure that a session variable is set before you attempt to use it <?php session_start(); if (isset($_session['firstname']) && isset($_session['lastname']) && isset($_session['occupation'])) echo "<p>". $_SESSION['firstName']. " ". $_SESSION['lastName']. " is a ". $_SESSION['occupation']. "</p>";?> Deleting a Session To delete a session manually, perform the following steps: 1. Execute the session_start() function 2. Use the array() construct to reinitialize the $_SESSION autoglobal 3. Use the session_destroy() function to delete the session 41 42 Deleting a Session Summary <?php session_start(); $_SESSION = array(); session_destroy();?> Information about individual visits to a Web site is called state information. Maintaining state means to store persistent information about Web site visits To pass form values from one PHP script to another, you can store the values in hidden form fields, which are submitted along with other types of form fields 43 44 11

Summary Summary One way to preserve information following a user s visit to a Web page is to append a query string to the end of a URL. To pass information from one Web page to another using a query string, add a question mark (?) immediately after a URL, followed by the query string containing the information you want to preserve in name/value pairs. Cookies, also called magic cookies, are small pieces of information about a user that are stored by a Web server in text files on the user s computer. Cookies can be temporary or persistent. Temporary cookies remain available only for the current browser session Persistent cookies remain available beyond the current browser session and are stored in a text file on a client computer 45 46 Summary Summary You use the setcookie() function to create cookies in PHP. You must call the setcookie() function before you send the Web browser any output, including white space, HTML elements, or output from the echo or print statements. Cookies created with only the name and value arguments of the setcookie() function are temporary cookies, because they are available for only the current browser session 47 For a cookie to persist beyond the current browser session, you must use the expires argument with the setcookie() function The path argument of the setcookie() function determines the availability of a cookie to other Web pages on a server The secure argument of the setcookie() function indicates that a cookie can only be transmitted across a secure Internet connection using HTTPS or another security protocol 48 12

Summary Summary To delete a persistent cookie before the time elapses in the assigned expires argument, assign a new expiration value to a time in the past and clearing the value. You do this by subtracting any number of seconds from the time() function and setting the value of the cookie to the empty string. Sessions refer to periods of activity when a PHP script stores state information on a Web server. When you start a new session, the session_start() function generates a unique session ID to identify the session. If a client s Web browser is configured to accept cookies, the session ID is assigned to a temporary cookie named PHPSESSID. 49 50 Summary Summary You must call the session_start() function before you send the Web browser any output, including white space, HTML elements, or output from the echo or print statements You store session state information in the $_SESSION[] autoglobal To delete a session, execute the session_start() function, use the array[] construct to reinitialize the $_SESSION[] autoglobal and call the session_destroy() function 51 52 13