Cookies, Sessions, and Authentication Dr. Charles Severance www.php-intro.com.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Cookies, Sessions. Server Side Includes You can insert the content of one file into another file before the server executes it, with the require() function.
Lecture 6/2/12. Forms and PHP The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input When dealing with HTML forms.
Getting PHP Hosting Dr. Charles Severance. What We Need We want to be able to put up our application on the web so anyone can access our URL (and so we.
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
1 The World Wide Web. 2  Web Fundamentals  Pages are defined by the Hypertext Markup Language (HTML) and contain text, graphics, audio, video and software.
Forms and PHP Dr. Charles Severance
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
1 Web Developer & Design Foundations with XHTML Chapter 6 Key Concepts.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Cookies & Sessions.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
CSC 2720 Building Web Applications Cookies, URL-Rewriting, Hidden Fields and Session Management.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
1 Maryland ColdFusion User Group Session Management December 2001 Michael Schuler
Nic Shulver, Introduction to Sessions in PHP Sessions What is a session? Example Software Software Organisation The login HTML.
1 Chapter 9 – Cookies, Sessions, FTP, and More spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science.
Cookies & Session Web Technology
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
PHP. $_GET / $_POST / $_SESSION PHP uses predefined variables to provide access to important information about the server and requests from a browser.
Sessions in PHP – Page 1 of 13CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: Sessions in PHP Reading: Williams.
Web Database Programming Week 7 Session Management & Authentication.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Introduction to Dynamic Web Content Dr. Charles Severance
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Forms Overview, Query string, Submitting arrays, PHP & HTML, Input types, Redirecting the user Mario Peshev Technical Trainer Software.
Google App Engine Sessions and Cookies ae-09-session
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
PHP and Sessions. Session – a general definition The GENERAL definition of a session in the “COMPUTER WORLD” is: The interactions (requests and responses)
1 DIG 3134 Lecture 6: Maintaining State Michael Moshell University of Central Florida Media Software Design.
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
1 PHP HTTP After this lecture, you should be able to know: How to create and process web forms with HTML and PHP. How to create and process web forms with.
Forms and PHP Dr. Charles Severance
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Unit-6 Handling Sessions and Cookies. Concept of Session Session values are store in server side not in user’s machine. A session is available as long.
Session 11: Cookies, Sessions ans Security iNET Academy Open Source Web Development.
COOKIES AND SESSIONS.
LOGIN FORMS.
PHP: Further Skills 02 By Trevor Adams. Topics covered Persistence What is it? Why do we need it? Basic Persistence Hidden form fields Query strings Cookies.
Distributed Web Systems Cookies and Session Tracking Lecturer Department University.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
Sessions and cookies MIS 3501, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 4/12/2016.
Dr. Charles Severance Using Handlebars Dr. Charles Severance
C.R.U.D. Charles Severance
Introduction to Dynamic Web Content
CSE 154 Lecture 20: Cookies.
Forms and PHP.
Redirect, Routing, and Authentication
HTTP Parameters and Arrays
ITM 352 Cookies.
Cookies and Sessions Charles Severance
Unit 27 - Web Server Scripting
What is Cookie? Cookie is small information stored in text file on user’s hard drive by web server. This information is later used by web browser to retrieve.
CSE 154 Lecture 21: Cookies.
CSE 154 Lecture 21: Cookies.
Forms and PHP.
Introduction to Dynamic Web Content
HTTP GET vs POST SE-2840 Dr. Mark L. Hornick.
Cookies and sessions Saturday, February 23, 2019Saturday, February 23,
CSc 337 Lecture 27: Cookies.
CSE 154 Lecture 21: Cookies.
CSc 337 Lecture 25: Cookies.
Model View Controller (MVC)
Presentation transcript:

Cookies, Sessions, and Authentication Dr. Charles Severance

High Level Summary The web is “stateless” - the browser does not maintain a connection to the server while you are looking at a page. You may never come back to the same server - or it may be a long time - or it may be one second later So we need a way for servers to know “which browser is this?” In the browser state is stored in “Cookies” In the server state is stored in “Sessions”

Other Web sites always seem to know who you are!

Multi-User When a server is interacting with many different browsers at the same time, the server needs to know *which* browser a particular request came from Request / Response initially was stateless - all browsers looked identical - this was really really bad and did not last very long at all.

Web Cookies to the Rescue Technically, cookies are arbitrary pieces of data chosen by the Web server and sent to the browser. The browser returns them unchanged to the server, introducing a state (memory of previous events) into otherwise stateless HTTP transactions. Without cookies, each retrieval of a Web page or component of a Web page is an isolated event, mostly unrelated to all other views of the pages of the same site.

Cookies In the Browser Cookies are marked as to the web addresses they come from - the browser only sends back cookies that were originally set by the same web server Cookies have an expiration date - some last for years - others are short-term and go away as soon as the browser is closed

In a fresh browser.

Sessions

In The Server - Sessions In most server applications, as soon as we meet a new browser - we create a session We set a session cookie to be stored in the browser which indicates the session id in use The creation and destruction of sessions is handled by a web framework or some utility code that we just use to manage the sessions

Session Identifier A large, random number that we place in a browser cookie the first time we encounter a browser. This number is used to pick from the many sessions that the server has active at any one time. Server software stores data in the session which it wants to have from one request to another from the same browser. Shopping cart or login information is stored in the session in the server

PHP Sessions

We can establish / initialize a PHP Session by calling session_start() before any output has come out If the user has cookies set, we can use the array $_SESSION to store data from one request to the next with a particular browser We have a bit of data that persists from one request to the next By default these are stored in a temporary folder on disk

(On a Mac) /Applications/MAMP/tmp/php

<?php // Note - cannot have any output before this session_start(); if ( ! isset($_SESSION['value']) ) { echo(" Session is empty \n"); $_SESSION['value'] = 0; } else if ( $_SESSION['value'] < 3 ) { $_SESSION['value'] = $_SESSION['value'] + 1; echo(" Added one... \n"); } else { session_destroy(); session_start(); echo(" Session Restarted \n"); } ?> Click Me! Our Session ID is: sessfun.php

POST / Redirect / GET Once you do a POST, if you do refresh, the browser will re-send the POST data a second time The user gets a popup that tries to explain what is about to happen

guess.php Press Refresh

No Double Posts Typically POST requests are adding or modifying data whilst GET requests view data It may be dangerous to do the same POST twice (say withdrawing funds from a bank account) So the browser insists on asking the user (out of your control) Kind of an ugly UX / bad usability

HTTP Location Header If your application has not yet sent any data, it can send a special header as part of the HTTP Response The redirect header includes a URL that the browser is supposed to forard itself to It was originally used for web sites that moved from one URL to another

<= Error

<?php session_start(); if ( isset($_POST['where']) ) { if ( $_POST['where'] == '1' ) { header("Location: redir1.php"); return; } else if ( $_POST['where'] == '2' ) { header("Location: redir2.php?parm=123"); return; } else { header("Location: return; } ?> I am Router Two... Where to go? (1-3) redir1.php

After we entered "2" and pressed "Submit" Two pages were retrieved

Second page

POST Redirect Rule The simple rule for pages intended for a browser is to never generate a page with HTML content when the app receives POST data Must redirect somewhere - even to the same script - forcing the browser to make a GET after the POST

guess.php <?php $guess = ''; $message = false; if ( isset($_POST['guess']) ) { // Trick for integer / numeric parameters $guess = $_POST['guess'] + 0; if ( $guess == 42 ) { $message = "Great job!"; } else if ( $guess < 42 ) { $message = "Too low"; } else { $message = "Too high..."; } ?> A Guessing game Guessing game... <?php if ( $message !== false ) { echo(" $message \n"); } ?> Input Guess <input type="text" name="guess" id="guess" size="40" <?php echo 'value="'. htmlentities($guess). '"'; ?> /> (Review)

<?php $guess = ''; $message = false; if ( isset($_POST['guess']) ) { // Trick for integer / numeric parameters $guess = $_POST['guess'] + 0; if ( $guess == 42 ) { $message = "Great job!"; } else if ( $guess < 42 ) { $message = "Too low"; } else { $message = "Too high..."; } ?> A Guessing game Guessing game... <?php if ( $message !== false ) { echo(" $message \n"); } ?> Input Guess <input type="text" name="guess" id="guess" size="40" <?php echo 'value="'. htmlentities($guess). '"'; ?> /> <?php $guess = ''; $message = false; if ( isset($_POST['guess']) ) { // Nifty trick $guess = $_POST['guess'] + 0; if ( $guess == 42 ) { $message = "Great job!"; } else if ( $guess < 42 ) { $message = "Too low"; } else { $message = "Too high..."; } ?>... guess.php (Review)

<?php $guess = ''; $message = false; if ( isset($_POST['guess']) ) { // Trick for integer / numeric parameters $guess = $_POST['guess'] + 0; if ( $guess == 42 ) { $message = "Great job!"; } else if ( $guess < 42 ) { $message = "Too low"; } else { $message = "Too high..."; } ?> A Guessing game Guessing game... <?php if ( $message !== false ) { echo(" $message \n"); } ?> Input Guess <input type="text" name="guess" id="guess" size="40" <?php echo 'value="'. htmlentities($guess). '"'; ?> />... ?> A Guessing game Guessing game... <?php if ( $message !== false ) { echo(" $message \n"); } ?> Input Guess <input type="text" name="guess" id="guess" size="40" <?php echo 'value="'. htmlentities($guess). '"'; ?> /> (Review)

<?php session_start(); if ( isset($_POST['guess']) ) { $guess = $_POST['guess'] + 0; $_SESSION['guess'] = $guess; if ( $guess == 42 ) { $_SESSION['message'] = "Great job!"; } else if ( $guess < 42 ) { $_SESSION['message'] = "Too low"; } else { $_SESSION['message'] = "Too high..."; } header("Location: guess2.php"); return; } ?> guess2.php (Improved)

A Guessing game <?php $guess = isset($_SESSION['guess']) ? $_SESSION['guess'] : ''; $message = isset($_SESSION['message']) ? $_SESSION['message'] : false; ?> Guessing game... <?php if ( $message !== false ) { echo(" $message \n"); } ?> Input Guess <input type="text" name="guess" id="guess" size="40" /> guess2.php

Enter "41" and press "Submit"

Press "Refresh"

Login / Logout Having a session is not the same as being logged in. Generally you have a session the instant you connect to a web site The Session ID cookie is set when the first page is delivered Login puts user information in the session (stored in the server) Logout removes user information from the session

Simple address book with session as storage.

<?php session_start(); if ( isset($_POST["account"]) && isset($_POST["pw"]) ) { unset($_SESSION["account"]); // Logout current user if ( $_POST['pw'] == 'umsi' ) { $_SESSION["account"] = $_POST["account"]; $_SESSION["success"] = "Logged in."; header( 'Location: index.php' ) ; return; } else { $_SESSION["error"] = "Incorrect password."; header( 'Location: login.php' ) ; return; } ?> login.php

?> Please Log In <?php if ( isset($_SESSION["error"]) ) { echo(' Error:'. $_SESSION["error"]." \n"); unset($_SESSION["error"]); } ?> Account: Password: login.php

<?php session_start(); session_destroy(); header("Location: index.php"); logout.php

?> Online Address Book <?php if ( isset($_SESSION["success"]) ) { echo(' '.$_SESSION["success"]." \n"); unset($_SESSION["success"]); } // Retrieve data from the session for the view $street = isset($_SESSION['street']) ? $_SESSION['street'] : ''; $city = isset($_SESSION['city']) ? $_SESSION['city'] : ''; $state = isset($_SESSION['state']) ? $_SESSION['state'] : ''; $zip = isset($_SESSION['zip']) ? $_SESSION['zip'] : ''; index.php

if ( ! isset($_SESSION["account"]) ) { ?> Please Log In to start. Please enter your address: Street: <input type="text" name="street" size="50" value=" "> City: <input type="text" name="city" size="20" value=" "> State: <input type="text" name="state" size="2" value=" "> Zip: <input type="text" name="zip" size="5" value=" "> <input type="button" value="Logout" onclick="location.href='logout.php'; return false"> index.php

<?php session_start(); if ( isset($_POST["street"]) && isset($_POST["city"]) && isset($_POST["state"]) && isset($_POST["zip"]) ) { $_SESSION['street'] = $_POST['street']; $_SESSION['city'] = $_POST['city']; $_SESSION['state'] = $_POST['state']; $_SESSION['zip'] = $_POST['zip']; header( 'Location: index.php' ); return; } ?> index.php

PHP Sessions Without Cookies For a simple application handling login, logout, and shopping cart like information, cookie sessions are sufficient But if an application needs to function within an iframe, or have more than one session active (i.e. multiple tabs to the same site) we cannot use session cookies PHP has nice support for maintaining a sessions without a cookie

nocookie.php

<?php // Tell PHP we won't be using cookies for the session ini_set('session.use_cookies', '0'); ini_set('session.use_only_cookies',0); ini_set('session.use_trans_sid',1); session_start(); // Start the view ?> No Cookies for You! nocookie.php

No Cookies for You! <?php if ( ! isset($_SESSION['value']) ) { echo(" Session is empty \n"); $_SESSION['value'] = 0; } else if ( $_SESSION['value'] < 3 ) { $_SESSION['value'] = $_SESSION['value'] + 1; echo(" Added one \$_SESSION['value']=".$_SESSION['value']. " \n"); } else { session_destroy(); session_start(); echo(" Session Restarted \n"); } ?> Click This Anchor Tag! nocookie.php

?> Click This Anchor Tag! Our Session ID is: nocookie.php

A whole host of problems... Session id is not automatically added in JavaScript, Ajax, Redirect, or other elements of HTML With the session id on the URL, folks can URLs or even bookmark them and be logged in We will come back to these...

Summary Cookies Sessions Sessions in PHP Login / Logout POST / Redirect Pattern Cookie-free sessions

Acknowledgements / Contributions These slides are Copyright Charles R. Severance ( as part of and made available under a Creative Commons Attribution 4.0 License. Please maintain this last slide in all copies of the document to comply with the attribution requirements of the license. If you make a change, feel free to add your name and organization to the list of contributors on this page as you republish the materials. Initial Development: Charles Severance, University of Michigan School of Information Insert new Contributors and Translators here including names and dates Continue new Contributors and Translators here