Cookies and Sessions Cookies are useful for storing user info that should be retained from one page to the next. (Overcome the ‘stateless’ nature of the.

Slides:



Advertisements
Similar presentations
LIS651 lecture 3 taming PHP Thomas Krichel
Advertisements

LIS651 lecture 3 functions & sessions Thomas Krichel
PHP I.
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.
Java Script Session1 INTRODUCTION.
PHP and the Web: Session : 4. Predefined variables PHP provides a large number of predefined global variables to any script which it runs also called.
PHP (2) – Functions, Arrays, Databases, and sessions.
Cookies and Sessions Cookies are useful for storing user info that should be retained from one page to the next. (Overcome the ‘stateless’ nature of the.
Chapter 10 Managing State Information PHP Programming with MySQL.
CP3024 Lecture 5 State Maintenance, Cascading Style Sheets and Dynamic HTML.
Using Session Control in PHP tMyn1 Using Session Control in PHP HTTP is a stateless protocol, which means that the protocol has no built-in way of maintaining.
CSE 154 LECTURE 13: SESSIONS. Expiration / persistent cookies setcookie("name", "value", expiration); PHP $expireTime = time() + 60*60*24*7; # 1 week.
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
1 Cookies & Session Variables. 2 Managing Sessions and Using Session Variables You may have heard that HTTP, the protocol on which the Web runs, is a.
Modified from Moseley ’s sli desWeb Applications Development. Lecture 6 Slide 1 Lecture 6: More PHP Instructor: Dr. Mohammad Anwar Hossain.
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.
Cookies Set a cookie – setcookie() Extract data from a cookie - $_COOKIE Augment user authentication script with a cookie.
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.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
JavaScript, Fourth Edition
First Name Last Name Please enter your logon information: John Submit Chen Web Server Login.php Web Server Hello John Chen Greetings. php Please enter.
Week 9 PHP Cookies and Session Introduction to JavaScript.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Chapter 8 Cookies And Security JavaScript, Third Edition.
12/3/2012ISC329 Isabelle Bichindaritz1 PHP and MySQL Advanced Features.
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.
NMD202 Web Scripting Week3. What we will cover today Includes Exercises PHP Forms Exercises Server side validation Exercises.
Nic Shulver, Introduction to Sessions in PHP Sessions What is a session? Example Software Software Organisation The login HTML.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
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.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
Cookies & Session Web Technology
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
Prof Frankl, Spring 2008CS Polytechnic University 1 Overview of Web database applications with PHP.
PHP Workshop ‹#› Maintaining State in PHP Part II - Sessions.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
SessionsPHPApril 2010 : [‹#›] Maintaining State in PHP Part II - Sessions.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Web Database Programming Week 7 Session Management & Authentication.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
PHP Session ISYS 475. Session The web server starts a session when a visitor visiting your web site and assigns a unique id, the session id for the session.
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)
 A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests.
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.
PHP Form Processing * referenced from
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.
HTTP Transactions 1. 2 Client-Server Model 3 HTTP HyperText Transport Protocol Native protocol for WWW Sits on top of internet’s TCP/IP protocol HTTP.
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.
PHP. Outline  What is PHP?  What can PHP do?  PHP Basics  PHP and Forms  Cookies and Sessions  Database Connections  Command.
Unit 4 Working with data. Form Element HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons,
Programming for the Web Cookies & Sessions Dónal Mulligan BSc MA
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
19.10 Using Cookies A cookie is a piece of information that’s stored by a server in a text file on a client’s computer to maintain information about.
ITM 352 Cookies.
Maintaining State in PHP Part II - Sessions
Open Source Programming
<?php require("header.htm"); ?>
Maintaining State in PHP Part II - Sessions
SESSION TRACKING BY DINESH KUMAR.R.
Cookies and Sessions.
Presentation transcript:

Cookies and Sessions Cookies are useful for storing user info that should be retained from one page to the next. (Overcome the ‘stateless’ nature of the web) Cookies are written to the client’s hard drive. Problems: –User can disable cookies in the browser –Cookies may be viewed by other users –Can only store 20 cookies; max 4KB. –Some browsers may display incorrectly unless all options are set in setcookie() (eg expiration time, path) –C:\documents and

Creating a cookie setcookie(name,value,expiration); –Eg, setcookie(“fruit”,”banana”,time()+3600); The cookie is called ‘fruit’ and has a value of ‘banana’; it will expire 1 hr from now. –Eg. setcookie(“username”,”jceddia”,time()+1800); Cookie values are sent as part of the HTTP headers (transparent to user). No output should be sent to the browser (echo etc) until the cookie is set else cookie will not be set.

Accessing A Cookie Once created,cookie values are automatically available to PHP scripts as a variable having the same name as the cookie. –Eg. echo “the current user is $username”; Php associative array HTTP_COOKIE_VARS contain the value of every current cookie Foreach ($HTTP_COOKIE_VARS as $name =>$value) echo “ $name => $value”;

Cookie examples <?php // set an individual cookie $value = 'something from somewhere'; setcookie ("TestCookie", $value); setcookie ("TestCookie", $value,time()+3600); /* expire in 1 hour */ setcookie ("TestCookie", $value,time()+3600, "/~rasmus/", ".example.com", 1); ?> <?php // Print an individual cookie echo $_COOKIE["TestCookie"]; echo $HTTP_COOKIE_VARS["TestCookie"]; ?>

Deleting a Cookie Automatically deleted after expiration time Can manually delete by setting negative time setcookie(“username”,””,time()-3600); Other cookie options setcookie( name,value,expire,path,domain,secure ) path=which scripts have access to cookie values?. By default, any script in the current server directory downward have access. Parent directory doesn’t.

Other cookie options domain = by default, a cookie is only available to scripts on the current web server. Specify a domain name for other servers. NOTE that some browsers need at least two dots in the domain name (Netscape). secure = how cookies are sent. 1 = https (secure connection) 0 = http (normal connection) php has Mcrypt functions. Eg. setcookie(“username”,”jceddia”,time()+3600,”/webroot”, ”

Redirection Once login data is captured/validated then want to go to a new page. Header(“Location: URL”); header("Location: p-6-2.html"); General technique: –Site start page = login page –Login page validates user and set cookies –Redirect to new page –New page uses cookie data to access DB info

Sessions What if user disables cookies? Need to store data on the server. This is done in session variables. A session variable is a regular global variable that, when registered as a session variable, keeps its value on all pages that use PHP4 sessions. To register a session variable: – assign a value to a variable that is to become a session variable $mysessvar = “somevalue” –and call session_register(“mysessvar"). –On all subsequent pages that use sessions (by calling session_start()), the variable mysessvar will have the value assigned to it.

Session cont. –A visitor accessing your web site is assigned an unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. –The session support allows you to register arbitrary numbers of variables to be preserved across requests. When a visitor accesses your site, PHP will check automatically (if session.auto_start is set to 1) or on your request (explicitly through session_start() or implicitly through session_register()) whether a specific session id has been sent with the request. If this is the case, the prior saved environment is recreated. –All registered variables are serialized after the request finishes. Registered variables which are undefined are marked as being not defined. On subsequent accesses, these are not defined by the session module unless the user defines them later.

–The track_vars and register_globals configuration settings influence how the session variables get stored and restored.track_varsregister_globals –Note: As of PHP 4.0.3, track_vars is always turned on.track_vars –Note: As of PHP 4.1.0, $_SESSION is available as global variable just like $_POST, $_GET, $_REQUEST and so on. Not like $HTTP_SESSION_VARS, $_SESSION is always global. Therefore, global should not be used for $_SESSION. –If register_globals is enabled, then all global variables can be registered as session variables and the session variables will be restored to corresponding global variables. Since PHP must know which global variables are registered as session variables, users must register variables with session_register() function while $HTTP_SESSION_VARS/$_SESSION do not need to use session_register(). –See php manual for further explanation of track_vars and register_globalsphp manual

Example 1. Registering a variable with track_vars enabled <?php if (isset($HTTP_SESSION_VARS['count'])) { $HTTP_SESSION_VARS['count']++; } else { $HTTP_SESSION_VARS['count'] = 0; } ?> Use of $_SESSION (or $HTTP_SESSION_VARS with PHP or less) is recommended for security and code readablity. Disabling register_globals is recommended for both security and performance reason.

–With $_SESSION or $HTTP_SESSION_VARS, there is no need to use session_register() or session_unregister() or session_is_registered() functions. Users can access session variables like a normal variables. –Example 2. Registering a variable with $_SESSION. <?php // Use $HTTP_SESSION_VARS with PHP or less if (!isset($_SESSION['count'])) { $_SESSION['count'] = 0; } else { $_SESSION['count']++; } ?>

Example 3. Unregistering a variable with $_SESSION. <?php // Use $HTTP_SESSION_VARS with PHP or less unset($_SESSION['count']); ?>

Session Ids. There are two methods to propagate a session id: – Cookies – URL parameter –The session module supports both methods. Cookies are optimal, but since they are not reliable (clients are not bound to accept them), we cannot rely on them. The second method embeds the session id directly into URLs. – PHP is capable of doing this transparently when compiled with --enable-trans-sid. If you enable this option, relative URIs will be changed to contain the session id automatically. Alternatively, you can use the constant SID which is defined, if the client did not send the appropriate cookie. SID is either of the form session_name=session_id or is an empty string.

Sid’s –The following example demonstrates how to register a variable, and how to link correctly to another page using SID. Example 5. Counting the number of hits of a single user <?php if (!session_is_registered('count')) { session_register('count'); $count = 1; } else { $count++; } ?> Hello visitor, you have seen this page times. ;

Sid’s cont. <?php # the ( can be used if short tag is enabled) # is necessary to preserve the session id # in the case that the user has disabled cookies ?> To continue, ">click here The is not necessary, if --enable-trans- sid was used to compile PHP. Note: Non-relative URLs are assumed to point to external sites and hence don't append the SID, as it would be a security risk to leak the SID to a different server.

Session functions –session_start -- Initialize session data –session_destroy -- Destroys all data registered to a session –session_name -- Get and/or set the current session name –session_module_name -- Get and/or set the current session module –session_save_path -- Get and/or set the current session save path –session_id -- Get and/or set the current session id –session_register -- Register one or more variables with the current session –session_unregister -- Unregister a variable from the current session –session_unset -- Free all session variables –session_is_registered -- Find out if a variable is registered in a session –session_get_cookie_params -- Get the session cookie parameters –session_set_cookie_params -- Set the session cookie parameters –session_decode -- Decodes session data from a string –session_encode -- Encodes the current session data as a string –session_set_save_handler -- Sets user-level session storage functions –session_cache_limiter -- Get and/or set the current cache limiter –session_cache_expire -- Return current cache expire –session_write_close -- Write session data and end session

Session_start() All pages that uses PHP4 sessions must call the function session_start() to tell the PHP4 engine to load session related information into memory. The session_start() function tries to find the session id in the cookie field or the request parameters for the current HTTP request. If it cannot find the session id, a new session is created.

Session_register() The first example (page1.php): <?php session_start(); $my_session_variable = "some value"; session_register("my_session_variable"); ?> //may also use $_SESSION[‘my_session_var'] = “somevalue”;

–What this does is that it registers the variable my_session_variable as a session variable. This means that the variable will be alive (keep it's value) across page-accesses, as long as you call the session_start() function on all pages that need access to the my_session_variable variable. Example 2 (page2.php): <?php session_start(); print "Value of 'my_session_variable': $my_session_variable"; ?>

Using session variables for authentication in conjunction with a database. Create a login-page gives the user a userid and password form and posts to another PHP page (this example uses mysql): <?php session_start(); if ($userid && $password) { $res = mysql_query("SELECT userid FROM users WHERE userid='$userid' AND password='$password'"); if(mysql_num_rows($res) != 0) { $verified_user = $userid; session_register("verified_user"); } Header("Location: your_main_page.php"); ?> Now, on 'your_main_page.php', you call session_start() and then you can check the verified_user variable to see if the user has been authenticated (and who he is). Other uses for session variables, easing database load by caching certain values in the session rather than reading them from the database on each page access.

Example 2 – register user –Just to make explicit what probably others have already figured out from the documentation, only global variables can be stored in the session. Any variable that you manipulate in a function must be declared global if you want to store it in the session, and any session variable that you need access to must be declared global. For example, session_start(); function confirmUserLogin ($postLoginUrl) // Function to check login { // To get access to this session var, I must declare it global. global $session_userID; if (!IsSet($session_userID)) { session_register('session_post_login_page'); // To set this session var, I must declare it global. global $session_post_login_page; $session_post_login_page = $postLoginUrl; redirect("/login/"); } }

Destroying a session <?php // Initialize the session. session_start(); // Unset all of the session variables. session_unset(); // Finally, destroy the session. session_destroy(); ?>

Destroying a session - $_SESSION <?php // Initialize the session. session_start(); // Unset all of the session variables. $_SESSION = array(); // Finally, destroy the session. session_destroy(); ?> ** See example by Christopher Fryer.

Templates Templates allow the separation of php code from html Useful on large sites where graphic designers manipulate html and php programmers write code Sample Template The answer to today’s question is {ANSWER}. {ANSWER} is a template variable which is ‘evaluated’ when the page is fetched

To Use Templates - do Create a template file Create a php script that fills in the template by 1.Instantiate a template object (template.inc) 2.Associate a template variable with the template file (.tpl extension) 3.Assign values to template variables ( 4.Parse the template variable associated with the template file 5.Print the value of the template containing the result.

Template Example. Assume that there is a template in the /home/mydir/mytemplates/ named MyTemplate.tpl that has some text that reads something like this: Congratulations! You won a new {some_color} Book! "{some_color}" has curly braces around it. The curly braces indicate that some_color is a template variable. A PHP script that will load the template, insert the value of the PHP variable $my_color where the {some_color} template variable tag is, and then output the new text. If $my_color happens to be set to "blue", the final output should look like: Congratulations! You won a new blue Book!

Template Example cont. <?php include "template.inc"; $my_color = "blue"; // we'll use this later $t = new Template("/home/mydir/mytemplates/"); // create a template object named $t $t->set_file("MyFileHandle","MyTemplate.tpl"); // set MyFileHandle = our template file $t->set_var("some_color",$my_color); // set template variable some_color = $my_color value $t->parse("MyOutput","MyFileHandle"); // set template variable MyOutput = parsed file $t->p("MyOutput"); // output the value of MyOutput (our parsed data) ?>

Template Example cont. NOTE: The path ("/home/mydir/mytemplates/") in the Template constructor call sets the root path where your templates are located, but if you leave it out it defaults to the same directory as your PHP script. Nothing is output to the web server until p("MyOutput") is called, which outputs the final parsed text.

Nested Templates A feature of the parse() function is that the MyOutput handle that it created is actually a template variable, just as {some_color} is a template variable. So if you have another template with a {MyOutput} tag, when you parse that second template, all of the {MyOutput} tags will be replaced with the parsed text from MyOutput. This lets you embed the text of one template file into another template. So, we could have another template called wholePage.tpl that contains the text: Sorry you didn't win. But if you had won, we would have told you: {MyOutput} And after wholePage.tpl is parsed, the final output would be: Sorry you didn't win. But if you had won, we would have told you: Congratulations! You won a new blue Book!

Nested template example <?php $t = new Template("/home/mydir/mytemplates/"); // These three lines are the same as the first example: $t->set_file("MyFileHandle","MyTemplate.tpl"); $t->set_var("some_color",$my_color); $t->parse("MyOutput","MyFileHandle"); // (Note that we don't call p() //here, so nothing gets output yet.) // Now parse a second template: $t->set_file("WholeHandle","wholePage.tpl"); // wholePage.ihtml has "{MyOutput}" in it $t->parse("MyFinalOutput","WholeHandle"); // All {MyOutput}'s get replaced $t->p("MyFinalOutput"); // output the value of MyFinalOutput ?>

Template Array parameters parse() and p() can be combined using the shorter function pparse() replacing the last two lines with The functions set_file() and set_var() can also accept multiple sets of values at a time by passing an array of handle/value pairs. Here are examples: <?php $t->set_file(array( "pageOneHandle" => "pageone.tpl", "pageTwoHandle" => "pagetwo.tpl")); $t->set_var(array( "last_name" => "Gates", "first_name" => "Bill", "net_worth" => $reallybignumber)); ?>

Appending Template Text A third parameter that you can pass to parse() and pparse() if you want to append data to the template variable rather than overwrite it. Simply call parse() or pparse() with the third parameter as true, such as parse("MyOutput","MyFileHandle", true); ?> If MyOutput already contains data, MyFileHandle will be parsed and appended onto the existing data in MyOutput. This technique is useful if you have a template where you want the same text to be repeated multiple times, such as listing multiple rows of results from a database query.

Example <?php $t = new Template("/home/mydir/mytemplates/"); $t->set_file(array( "mainpage" => "mainpage.tpl", "each_element" => "each_element.tpl")); reset($myArray); while (list($elementName, $elementValue) = each($myArray)) { // Set 'value' and 'name' to each element's value and name: $t->set_var("name",$elementName); $t->set_var("value",$elementValue); // Append copies of each_element: $t->parse("array_elements","each_element",true); } $t->pparse("output","mainpage"); ?>

Example cont. This example uses two templates, mainpage.tpl and each_element.tpl. The mainpage.tpl template could look something like this: Here is the array: {array_elements} The {array_elements} tag above will be replaced with copies of each_element.tpl, which is repeated for each element of the array ($myArray). The each_element.tpl template might look like this: {name}: {value} The result is a formatted table of the elements of $myArray.

Constructing a complete web site A typical web page includes elements such as: –Headers : appear at the top of the page –Navigation bar : below the header or on LHS of page –Content : in the center of the page –Footers : at the bottom of the page For consistency across the whole site it is usual to create a template that ‘describes’ each element and an additional template file describing the way these elements are combined.

Example - Std.tpl {title} {header} {leftnav} {content}

Example - header.tpl The Generic Web Site

Example - leftnav.tpl Home Function 1 Function 2 Logout

Example - index.tpl Welcome to the {title}! This is where you'll find information about absolutely nothing. We're so sure you won't find anything of interest here, we'll pay you if you can show us we're wrong.

Example - index.php <?php include 'template.inc'; $tpl = new Template('.'); //assume the templates are in the current directory $tpl->set_file(array('std' =>'std.tpl', 'header' =>'header.tpl', 'leftnav'=>'leftnav.tpl', 'content'=>'index.tpl')); $tpl->set_var('title', 'Generic Web Site'); $tpl->parse('header', 'header'); $tpl->parse('leftnav', 'leftnav'); $tpl->parse('content', 'content'); $tpl->parse('DUMMY', 'std'); $tpl->p('DUMMY'); ?>