Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

CookiesPHPMay-2007 : [‹#›] Maintaining State in PHP Part I - Cookies.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
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.
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.
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.
Chapter 10 Maintaining State Information Using Cookies.
Sys Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 15: PHP Introduction.
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.
About Dynamic Sites (Front End / Back End Implementations) by Janssen & Associates Affordable Website Solutions for Individuals and Small Businesses.
PHP Tutorial - Anas Jaghoub Chapter 2 Control Structures.
Advanced Web Forms with Databases Programming Right from the Start with Visual Basic.NET 1/e 13.
CSE 154 LECTURE 12: COOKIES. Including files: include include("filename"); PHP include("header.html"); include("shared-code.php"); PHP inserts the entire.
Web Programming Language Week 7 Dr. Ken Cosh Security, Sessions & Cookies.
Chapter 8 Cookies And Security JavaScript, Third Edition.
School of Computing and Information Systems CS 371 Web Application Programming PHP – Forms, Cookies, Sessions and Database.
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Chapter 6 Server-side Programming: Java Servlets
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
Web Scripting [PHP] CIS166AE Wednesdays 6:00pm – 9:50pm Rob Loy.
PHP Workshop ‹#› Maintaining State in PHP Part II - Sessions.
STATE MANAGEMENT.  Web Applications are based on stateless HTTP protocol which does not retain any information about user requests  The concept of state.
SessionsPHPApril 2010 : [‹#›] Maintaining State in PHP Part II - Sessions.
Dynamic Programming with PHP (mktime), Cookies, SQL, Authentication.
COOKIES and SESSIONS. COOKIES 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.
Cookies and Sessions IDIA 618 Fall 2014 Bridget M. Blodgett.
Saving State on the WWW. The Issue  Connections on the WWW are stateless  Every time a link is followed is like the first time to the server — it has.
PHP Cookies. Cookies are small files that are stored in the visitor's browser. Cookies can be used to identify return visitors, keep a user logged into.
ASP. What is ASP? ASP stands for Active Server Pages ASP is a Microsoft Technology ASP is a program that runs inside IIS IIS stands for Internet Information.
ECMM6018 Enterprise Networking for Electronic Commerce Tutorial 7
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
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)
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 1: Introduction to IS2803 Rob Gleasure
 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.
Web Page Designing With Dreamweaver MX\Session 1\1 of 9 Session 3 PHP Advanced.
Cookies and Sessions in PHP. Arguments for the setcookie() Function There are several arguments you can use i.e. setcookie(‘name’, ‘value’, expiration,
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.
Sessions and cookies (part 2) MIS 3501, Fall 2015 Brad N Greenwood, PhD Department of MIS Fox School of Business Temple University 11/19/2015.
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.
Fundamentals of Web DevelopmentRandy Connolly and Ricardo HoarFundamentals of Web DevelopmentRandy Connolly and Ricardo Hoar Fundamentals of Web DevelopmentRandy.
© Copyright 2012 Hidaya Trust (Pakistan) ● A Non-Profit Organization ● / www,histpk.org Hidaya Institute of Science & Technology
The need for persistence Consider these examples  Counting the number of “hits” on a website  i.e. how many times does a client load your web page source.
CSE 154 Lecture 20: Cookies.
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.
Sessions and cookies (part 2)
Maintaining State in PHP Part II - Sessions
Web Programming Language
Cookies and Sessions in PHP
Multitier Architecture, MySQL & PHP
Open Source Programming
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.
<?php require("header.htm"); ?>
Maintaining State in PHP Part II - Sessions
Web Programming Language
Cookies and Sessions.
PHP Forms and Databases.
Web Programming Language
Presentation transcript:

Lecture 7 Maintaining State (cookies & sessions) & MySQL Interaction (revisited)

Stateful v. Stateless "State" is a central concern of all sorts of distributed applications, but especially of Web applications. When applied to a protocol, "state" treats each series of interactions as having continuity, much like a single program's state. A "stateless" protocol is one in which there is no such continuity; each request must be processed entirely on its own merits. HTTP and its derivatives are intrinsically "stateless". The request/response cycle of a HTTP interaction does not maintain "memory" of any previous interactions.

Stateful v. Stateless (2) Stateful Interaction: Request 1: “What is Alice’s account number?” Response 1: Request 2: “What is her current balance?” Response 2: £ Stateless Interaction: Request 1: “What is Alice’s account number?” Response 1: Request 2: “What is Alice’s current balance?” Response 2: £345.65

Is PHP stateless? (well … yes) On a webserver, PHP scripts have no shared state, so each instance of a PHP script runs in its own logical memory space. The scripts maintain no persisted state, so each script start off fresh as a daisy, with no data to indicate what happened the previous times it was executed. Variables are destroyed as soon as the page script finishes executing. The script can access the ‘referrer’, the address of the previous page, although this can’t really be trusted. $_SERVER['HTTP_REFERER']

Is PHP stateless? (well … not necessarily) The usual way to maintain state in PHP scripts is via the use of sessions. To understand how these work, we need to have a look at what cookies are and how they work …

Client/Server interaction with Cookies A cookie is a small file that the server embeds on the user's browsers file system. Each time the same browser requests a page, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

Setting / Retrieving / Deleting a Cookie with PHP Setting a cookie : use the setcookie() function setcookie(name, value, expire, path, domain); Retrieve a cookie : use the $_COOKIE superglobal // Print a cookie echo $_COOKIE["name"]; // A way to view all cookies print_r($_COOKIE); Delete a cookie : set the time to a past instance // set the expiration date to one hour ago setcookie("name", "", time()-3600);

Title 1) { echo("This is visit number $visits."); } else { // First visit echo('Welcome to my Website! This is your first visit!'); } ?> Note : the cookie must be sent before any other headers. Setting & Retrieving a Cookie with PHP Run it

setcookie(name [,value [,expire [,path [,domain,secure]]]]]) name = cookie name value = data to store (string) expire = UNIX timestamp when the cookie expires. Default is that cookie expires when browser is closed. path = Path on the server within and below which the cookie is available on. domain = Domain at which the cookie is available for. secure = If cookie should be sent over HTTPS connection only. Default false. setcookie() keys & values

Each cookie on the user’s computer is connected to a particular domain. Each cookie can store up to 4kB of data. A maximum of 20 cookies can be stored on a user’s PC per domain Only strings can be stored in Cookie files. To store an array in a cookie, convert it to a string by using the serialize() PHP function. The array can be reconstructed using the unserialize() function once it had been read back in. Cookies are stored client-side, so never can’t be trusted completely: They can be easily viewed, modified or created by a 3 rd party. They can be turned on and off at will by the user. Cookie limits & notes

PHP Sessions Since HTTP is a stateless protocol – a PHP session can be used to store user information on the server for later use (i.e. username, shopping items, etc). Session information is temporary and will be deleted after the user has left the website. Session data can be made persistent by storing the data in a database. Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL (if cookies are turned off for instance).

CookiesSessions Limited storage spacePractically unlimited space Insecure storage client-sideReasonably securely stored server-side User controlledNo user control Cookies v. Sessions

session_start(); PHP does all the work: It looks for a valid session id in the $_COOKIE or $_GET superglobals – if found it initializes the data. If none found, a new session id is created. Note that like setcookie(), this function must be called before any echoed output to browser. Example session id: 26fe536a534d3c7cde4297abb45e275a Starting / Resuming a Session

The $_SESSION superglobal array can be used to store any session data. e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age; To retrieve session values, data is simply read back from the $_SESSION superglobal array. e.g. $name = $_SESSION[‘name’]; $age = $_SESSION[‘age’]; To delete session data – simply unset() a particular session variable e.g. unset($_SESSION[‘name’]); To destroy a session – use the session_destory() function e.g. session_destory(); Storing / Retrieving / Deleting Session data

Setting & Retrieving a Session value with PHP <?php session_start(); if(isset($_SESSION['visits'])) { $_SESSION['visits']=$_SESSION['visits']+1; } else { $_SESSION['visits']=1; } echo "This is visit number ". $_SESSION['visits']; ?> Run it

Typical process flow to save session data in a DB

PHP & DB Interaction with MySQL Open Source (relational) database server Runs on many platforms (Unix & Windows) Networked server – no fancy GUI like MS Access. You can find clients (such as phpMyAdmin) that provide a GUI. cems : (note: only available within uwe) Great for small, medium to large-sized applications (ebay, amazon, facebook etc. all make use of it) MySQL

phpMyAdmin A MySQL client written in PHP Via a browser you can manage: Manage Databases Manage MySQL users Submit queries (SQL) A great way to learn SQL!

There are three main API options when considering connecting to a MySQL database server: PHP's MySQL Extension - original extension which provides a procedural interface and is intended for use only with MySQL versions older than Can be used with versions of MySQL or newer, but not all of the latest MySQL server features will be available. PHP's mysqli Extension - MySQL improved extension takes advantage of new features found in MySQL versions and newer. The mysqli extension is included with PHP versions 5 and later. PHP Data Objects ( PDO ) - PHP Data Objects, or PDO, is a database abstraction layer that provides a consistent API regardless of the type of database server. In theory, it allows for the switch of the database server, from say Firebird to MySQL, with only minor changes the PHP code. PHP (main) API’s for using MySQL

Advantages of the mysqli API Object-oriented interface Support for Prepared Statements Support for Multiple Statements Support for Transactions Enhanced debugging capabilities Embedded server support Note: If using MySQL versions or later it is strongly recommended that the mysqli extension is used.

qidquoteauthordobdodurlcategory 1There is no remedy but to love more. Henry David Thoreau http://en.wikipedia.org/w iki/Henry_David_Thorea u love 6Work is the curse of the drinking classes. Oscar Wilde http://en.wikipedia.org/w iki/Oscar_wilde humour 11Religion is what keeps the poor from murdering the rich. Napoleon Bonaparte http://en.wikipedia.org/w iki/Napoleon politics example MySQL db Entity Model Example records (3)

// Connect to the db $mysqli = new mysqli('hostname','username','password','database'); //Send the query to the database and pull the records in a // certain category using the SELECT statement // If the result returns true if ($result = $mysqli->query("SELECT quote, url FROM quote WHERE category='love'")) { // print out the number of records retrieved echo 'For the category "love", there are '.$result->num_rows.' records. '; // The "fetch_object()" method allows access to the returned // rows within the resource object ($result in this case). while ($row = $result->fetch_object()) { echo 'Quote: '.$row->quote.' '; echo 'URL: url.'>'.$row->url. ' '; } else { // it’s an error & the query failed echo $mysqli->error; } // end else $mysqli->close(); example script using mysqli Run it

Update / delete/ add new record using mysqli – left as an exercise