SlideShare a Scribd company logo
Cookies, Sessions, and
Authentication
2
Server Side Includes
It is possible to insert the content of
one PHP file into another PHP file with
the include or require statement.
The include and require statements are
identical, except upon failure:
require will produce a fatal error
(E_COMPILE_ERROR) and stop the script
include will only produce a warning
(E_WARNING) and the script will continue
3
Server Side Includes
Syntax
<?php require("header.htm"); ?>
<?php include("footer.php");?>
How to create variables storing
values across php scripts’ calls?
Client-server connection is not permanent
=> Cannot be saved in program memory
There are many clients connecting
simultaneously
=> Cannot be saved in file (you cannot identify
clients as well sometimes)
.
.
.
Different mechanisms of the
same solution
 Cookies
 Cookies are a mechanism for storing data
in the remote browser and thus tracking or
identifying return users.
 Sessions
 Session support in PHP consists of a way
to preserve certain data across subsequent
accesses. This enables you to build more
customized applications and increase the
appeal of your web site.
What is a Cookie?
A cookie is a small file that the
server embeds on the user's
computer. Each time the same
computer requests for a page with
a browser, it will send the cookie
too. With PHP, you can both create
and retrieve cookie values.
How to Create a Cookie
The setcookie() function is used to create
cookies.
Note: The setcookie() function must
appear BEFORE the <html> tag.
setcookie(name, [value], [expire], [path],
[domain], [secure]);
This sets a cookie named "uname" - that expires after ten
hours.
<?php setcookie("uname", $name, time()+36000); ?>
<html> <body> …
How to Retrieve a Cookie
Value
 To access a cookie you just refer to the cookie
name as a variable or use $_COOKIE array
 Tip: Use the isset() function to find out if a
cookie has been set.
<html> <body>
<?php
if (isset($uname))
echo "Welcome " . $uname . "!<br />";
else
echo "You are not logged in!<br />"; ?>
</body> </html>
How to Delete a Cookie
 It will expire
or
 Cookies must be deleted with the same
parameters as they were set with. If the
value argument is an empty string (""),
and all other arguments match a
previous call to setcookie, then the
cookie with the specified name will be
deleted from the remote client.
What is a Session?
 The session support allows you to
register arbitrary numbers of variables
to be preserved across requests.
 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.
How to Create a Session
The session_start() function is
used to create cookies.
<?php
session_start();
?>
How do ‘Sessions’ work?
 They are based on assigning each user
a unique number, or session id. Even
for extremely heavy use sites, this
number can for all practical purposes
can be regarded as unique.
e.g.
26fe536a534d3c7cde4297abb45e275
a
How do ‘Sessions’ work?
 This session id is stored in a cookie, or
passed in the URL between pages
while the user browses.
 The data to be stored (e.g. name, log-in
state, etc.) is stored securely server-
side in a PHP superglobal, and
referenced using the session id.
Crucially, sessions are easy to
implement as PHP does all the
work!
Starting/Resuming a Session
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.
Starting/Resuming a Session
session_start();
When doing anything with sessions,
this is always called first!
Storing Session Data
 The $_SESSION superglobal array can
be used to store any session data.
e.g.
$_SESSION[‘name’] = $name;
$_SESSION[‘age’] = $age;
Reading Session Data
 Data is simply read back from the
$_SESSION superglobal array.
e.g.
$name = $_SESSION[‘name’];
$age = $_SESSION[‘age’];
Session Propagation
 Sessions need to pass the session id
between pages as a user browses to
track the session.
 It can do this in two ways:
 Cookie propagation
 URL propagation
How to Retrieve a Session Value
Register Session variable
session_register('var1','var2',...); // will also create a session
PS:Session variable will be created on using even if you will not register it!
Use it
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 0;
else
$_SESSION['count']++;
?>
Delete a Session Value
session_unregister(´varname´);
How to destroy a session:
session_destroy()
Destroying a Session
Often not required, but if we want to destroy a session:
// clear all session variables
$_SESSION = array();
// delete the session cookie if there is one
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(),'',time()-42000,'/');
}
// destroy session
session_destroy();
// avoid reusing the SID by redirecting
// back to the same page to regenerate session
header('Location: '.$_SERVER['PHP_SELF']);
Session Expiry
 By default, PHP sessions expire:
 after a certain length of inactivity (default 1440s), the
PHP garbage collection processes deletes session
variables. Important as most sessions will not be
explicitly destroyed.
 if propagated by cookies, default is to set a cookie
that is destroyed when the browser is closed.
 If URL propagated, session id is lost as soon as
navigate away from the site.
Long-term Sessions
 Although it is possible to customize
sessions so that they are maintained after
the browser is closed, for most practical
purposes PHP sessions can be regarded
as short-term.
 Long-term session data (e.g. ‘remember
me’ boxes) is usually maintained by
explicitly setting and retrieving cookie
data.
Using Cookies
 Cookies are small pieces of data that a
server sends to a browser for storage.
When a browser contacts a server, it
sends along any cookies for that server
under the variable $_COOKIES.
Similarly, a server can set one or more
cookies on the browser for retrieval at a
later time.
The first part of program session-cookies.php illustrates the typical use of cookies, with these lines:
 $today = date('l, F j, Y');
 $timestamp = date('g:i A');
 if (strcmp($_COOKIE[LAST_VISIT], "") == 0) {
 $lasttime = "";
 } else {
 $lasttime = $_COOKIE[LAST_VISIT];
 }
 $LAST_VISIT = $today . " at " . $timestamp;
 // set last_visit cookie with date/time, with expiration for 2 full weeks
 setcookie ("LAST_VISIT", $LAST_VISIT, time() + 3600*24*14);

 if ($_COOKIE[VISIT_NUMBER] == 0) {
 $visitcount = 0;
 } else {
 $visitcount = $_COOKIE[VISIT_NUMBER];
 }
 // set visit_number cookie with count, with expiration for 2 full weeks
 setcookie ("VISIT_NUMBER",1 + $visitcount, time() + 3600*24*14);
additional notes:
 Here are a few additional notes:
 Cookies are sent with Web page headers,
so any setting of cookies must take place
BEFORE the DOCTYPE line in an
HTML/PHP script.
 PHP function setcookie specifies a cookie
ID, a value, and a length of time for which
the cookie will be kept by the browser.
 PHP variable $_COOKIE is an associative
array that maintains the list of cookies set
previously.
Check if your browser is usually set to accept
cookies.
 If you use the Mozilla browser, this information can be found by
looking under "Preferences" in the "Edit" menu, and then going
to "Privacy & Security" and "Cookies".
 If you use the Iceweasel browser, this information can be found
by looking under "Preferences" in the "Edit" menu, and then
going to the "Privacy" tab.
 If you use Internet Explorer under Windows, this information can
be found by looking under select "Internet Options" from the
"Tools" menu, then look under "General" and "Settings" in the
"Temporary Internet Files" section.
 If you use Internet Explorer on a Macintosh, this information can
be found by looking under "Preferences" under the "Explorer"
menu, and then looking under "Cookies" in the "Receiving Files"
section.
Session Variables
 Effectively, session variables are cookies that
remain active only while the browser is actively
interacting with the server. When time elapses,
or when you close your browser, the session
variables disappear. (If cookies are not allowed
by a user, then information for sessions may be
placed in a query string at the end of a URL.)
 The following lines from session-cookies-
2.php illustrate typically processing of session
variables.
The following lines illustrate typically processing of session variables.
 // check if person has logged in previously
 session_start();
 $processingOK = "not yet";
 $firstLogin = "no";
 if (isset ($_SESSION['authorized'])) {
 // user already logged in
 $processingOK = $_SESSION['authorized'];
 } else {
 // user not logged in, so check password
 $password = trim($_POST['password']);
 if ($password == 'Test') {
 // correct password given
 $processingOK = 'ok';
 $_SESSION['authorized'] = 'ok';
 $firstLogin="yes";
 } else {
 // invalid password
 }
 }
Here are some notes regarding session variables:
 A script uses session_start() to initialize and register any
session variables.
 As with cookies, session variables are sent with Web
page headers, so any setting of session information
must take place before the DOCTYPE tag.
 PHP variable $_SESSION is an associative array that
maintains the list of session variables set previously.
 PHP function isset determines whether a
specific $_SESSION field has a designated value.
 PHP function unset removes a session value that was
sent previously, and session_unset() removes all
session values.
 <?php
 // Note - cannot have any output before this
 session_start();
 if ( ! isset($_SESSION['value']) ) {
 echo("<p>Session is empty</p>n");
 $_SESSION['value'] = 0;
 } else if ( $_SESSION['value'] < 3 ) {
 $_SESSION['value'] = $_SESSION['value'] + 1;
 echo("<p>Added one...</p>n");
 } else {
 session_destroy();
 session_start();
 echo("<p>Session Restarted</p>n");
 }
 ?>
 <p><a href="sessfun.php">Click Me!</a></p>
 <p>Our Session ID is: <?php echo(session_id()); ?></p>
 <pre>
 <?php print_r($_SESSION); ?>
 </pre>
http://www.php-intro.com/code/sessions/sessfun.php
http://www.php-intro.com/code/sessions/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
<?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: http://www.dr-chuck.com");
return;
}
}
?>
<html>
<body style="font-family: sans-serif;">
<p>I am Router Two...</p>
<form method="post">
<p><label for="inp9">Where to go? (1-3)</label>
<input type="text" name="where" id="inp9" size="5"></p>
<input type="submit"/></form>
</body>
http://www.php-intro.com/code/sessions/redir1.php
Approved
 <?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;
 }
 ?>
 <html>
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
http://www.php-intro.com/code/sessions
http://www.php-intro.com/code/sessions.zip
Simple address book with login,
logout, and session as storage.
POST-Redirect-GET-Flash
 POST detects error in
input data and puts a
message into
$_SESSION and
redirects
 GET sees the
message in the
session, displays it
and then deletes it
 Flash = "Seen once"
?><html>
<head></head>
<body style="font-family: sans-serif;">
<h1>Please Log In</h1>
<?php
if ( isset($_SESSION["error"]) ) {
echo('<p style="color:red">'.
$_SESSION["error"]."</p>n");
unset($_SESSION["error"]);
}
if ( isset($_SESSION["success"]) ) {
echo('<p style="color:green">'.
$_SESSION["success"]."</p>n");
unset($_SESSION["success"]);
}
?>
<form method="post">
<p>Account: <input type="text" name="account" value=""></p>
<p>Password: <input type="text" name="pw" value=""></p>
<p><input type="submit" value="Log In"></p>
</form>
</body>
login.php
<?php
session_start();
session_destroy();
header("Location: index.php");
logout.php
?><html><head></head>
<body style="font-family: sans-serif;">
<h1>Online Address Book</h1>
<?php
if ( isset($_SESSION["success"]) ) {
echo('<p style="color:green">'.$_SESSION["success"]."</p>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'] : '';
http://www.php-intro.com/code/sessions/index.php
if ( ! isset($_SESSION["account"]) ) { ?>
Please <a href="login.php">Log In</a> to start.
<?php } else { ?>
<p>Please enter your address:<form method="post">
<p>Street: <input type="text" name="street" size="50"
value="<?= echo(htmlentities($street) ?>"></p>
<p>City: <input type="text" name="city" size="20"
value="<?= echo(htmlentities($city) ?>"></p>
<p>State: <input type="text" name="state" size="2"
value="<?= echo(htmlentities($state) ?>">
Zip: <input type="text" name="zip" size="5"
value="<?= echo(htmlentities($zip) ?>"></p>
<p><input type="submit" value="Update">
<input type="button" value="Logout"
onclick="location.href='logout.php'; return false"></p>
</form>
<?php } ?>
</body>
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;
}
?><html>
index.php
Exercise
 Write a program called Web
page session-cookies.php that tries to
save a cookie to keep track of whether
or not you have visited this page
previously.

More Related Content

What's hot

PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
Vibrant Technologies & Computers
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
Lena Petsenchuk
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
tutorialsruby
 
Session php
Session phpSession php
Session php
200Hussain
 
Cookies & Session
Cookies & SessionCookies & Session
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
Kamal Acharya
 
Sessions and cookies in php
Sessions and cookies in phpSessions and cookies in php
Sessions and cookies in php
Pavan b
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
Gerard Sychay
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
ShingalaKrupa
 
Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with session
Firdaus Adib
 
php $_GET / $_POST / $_SESSION
php  $_GET / $_POST / $_SESSIONphp  $_GET / $_POST / $_SESSION
php $_GET / $_POST / $_SESSION
tumetr1
 
Cookies and Session
Cookies and SessionCookies and Session
Cookies and Session
KoraStats
 
java Cookies
java Cookiesjava Cookies
java Cookies
Rajanivetha G
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
Wim Godden
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
Hassen Poreya
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
amichoksi
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
apwebco
 
Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !
Wim Godden
 

What's hot (20)

PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
PHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and SessionsPHP - Introduction to PHP Cookies and Sessions
PHP - Introduction to PHP Cookies and Sessions
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Session php
Session phpSession php
Session php
 
Cookies & Session
Cookies & SessionCookies & Session
Cookies & Session
 
Session and Cookies
Session and CookiesSession and Cookies
Session and Cookies
 
Sessions and cookies in php
Sessions and cookies in phpSessions and cookies in php
Sessions and cookies in php
 
PHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and AuthenticationPHP Cookies, Sessions and Authentication
PHP Cookies, Sessions and Authentication
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 
Php - Getting good with session
Php - Getting good with sessionPhp - Getting good with session
Php - Getting good with session
 
php $_GET / $_POST / $_SESSION
php  $_GET / $_POST / $_SESSIONphp  $_GET / $_POST / $_SESSION
php $_GET / $_POST / $_SESSION
 
Cookies and Session
Cookies and SessionCookies and Session
Cookies and Session
 
java Cookies
java Cookiesjava Cookies
java Cookies
 
When dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniquesWhen dynamic becomes static: the next step in web caching techniques
When dynamic becomes static: the next step in web caching techniques
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
Web app development_cookies_sessions_14
Web app development_cookies_sessions_14Web app development_cookies_sessions_14
Web app development_cookies_sessions_14
 
Parameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHPParameter Passing & Session Tracking in PHP
Parameter Passing & Session Tracking in PHP
 
Web Cookies
Web CookiesWeb Cookies
Web Cookies
 
Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !Remove php calls and scale your site like crazy !
Remove php calls and scale your site like crazy !
 

Similar to Lecture8 php page control by okello erick

Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
pondypaiyan
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
HumphreyOwuor1
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
SreejithVP7
 
Manish
ManishManish
Manish
Manish Jain
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
Jalpesh Vasa
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
ShitalGhotekar
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
www.netgains.org
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
kunjan shah
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
salissal
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
ITNet
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
Degu8
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
Fatin Fatihayah
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
MattMarino13
 
PHP 2
PHP 2PHP 2
PHP 2
Richa Goel
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptx
ITNet
 
cookies.ppt
cookies.pptcookies.ppt
Php
PhpPhp
Session,cookies
Session,cookiesSession,cookies
Session,cookies
rkmourya511
 
Ph
PhPh

Similar to Lecture8 php page control by okello erick (20)

Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
 
PHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdfPHP-Cookies-Sessions.pdf
PHP-Cookies-Sessions.pdf
 
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.pptLecture 11 - PHP - Part 5 - CookiesSessions.ppt
Lecture 11 - PHP - Part 5 - CookiesSessions.ppt
 
Manish
ManishManish
Manish
 
4.4 PHP Session
4.4 PHP Session4.4 PHP Session
4.4 PHP Session
 
PHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptxPHP SESSIONS & COOKIE.pptx
PHP SESSIONS & COOKIE.pptx
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
season management in php (WT)
season management in php (WT)season management in php (WT)
season management in php (WT)
 
Cookies and sessions
Cookies and sessionsCookies and sessions
Cookies and sessions
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
FP512 Cookies sessions
FP512 Cookies sessionsFP512 Cookies sessions
FP512 Cookies sessions
 
javaScriptCookies.pptx
javaScriptCookies.pptxjavaScriptCookies.pptx
javaScriptCookies.pptx
 
PHP 2
PHP 2PHP 2
PHP 2
 
lecture 13.pptx
lecture 13.pptxlecture 13.pptx
lecture 13.pptx
 
cookies.ppt
cookies.pptcookies.ppt
cookies.ppt
 
Php
PhpPhp
Php
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
Ph
PhPh
Ph
 

More from okelloerick

My sql statements by okello erick
My sql statements by okello erickMy sql statements by okello erick
My sql statements by okello erick
okelloerick
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
okelloerick
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
okelloerick
 
Lecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erickLecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erick
okelloerick
 
Lecture4 php by okello erick
Lecture4 php by okello erickLecture4 php by okello erick
Lecture4 php by okello erick
okelloerick
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
okelloerick
 
Lecture3 mysql gui by okello erick
Lecture3 mysql gui by okello erickLecture3 mysql gui by okello erick
Lecture3 mysql gui by okello erick
okelloerick
 
Lecture2 mysql by okello erick
Lecture2 mysql by okello erickLecture2 mysql by okello erick
Lecture2 mysql by okello erick
okelloerick
 
Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erick
okelloerick
 
Data commn intro by okello erick
Data commn intro by okello erickData commn intro by okello erick
Data commn intro by okello erick
okelloerick
 
Computer networks--networking hardware
Computer networks--networking hardwareComputer networks--networking hardware
Computer networks--networking hardware
okelloerick
 

More from okelloerick (11)

My sql statements by okello erick
My sql statements by okello erickMy sql statements by okello erick
My sql statements by okello erick
 
Lecture7 form processing by okello erick
Lecture7 form processing by okello erickLecture7 form processing by okello erick
Lecture7 form processing by okello erick
 
Lecture6 display data by okello erick
Lecture6 display data by okello erickLecture6 display data by okello erick
Lecture6 display data by okello erick
 
Lecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erickLecture5 my sql statements by okello erick
Lecture5 my sql statements by okello erick
 
Lecture4 php by okello erick
Lecture4 php by okello erickLecture4 php by okello erick
Lecture4 php by okello erick
 
Lecture3 php by okello erick
Lecture3 php by okello erickLecture3 php by okello erick
Lecture3 php by okello erick
 
Lecture3 mysql gui by okello erick
Lecture3 mysql gui by okello erickLecture3 mysql gui by okello erick
Lecture3 mysql gui by okello erick
 
Lecture2 mysql by okello erick
Lecture2 mysql by okello erickLecture2 mysql by okello erick
Lecture2 mysql by okello erick
 
Lecture1 introduction by okello erick
Lecture1 introduction by okello erickLecture1 introduction by okello erick
Lecture1 introduction by okello erick
 
Data commn intro by okello erick
Data commn intro by okello erickData commn intro by okello erick
Data commn intro by okello erick
 
Computer networks--networking hardware
Computer networks--networking hardwareComputer networks--networking hardware
Computer networks--networking hardware
 

Recently uploaded

Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
Kumud Singh
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Malak Abu Hammad
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
ThomasParaiso2
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 

Recently uploaded (20)

Mind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AIMind map of terminologies used in context of Generative AI
Mind map of terminologies used in context of Generative AI
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfUnlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdf
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...GridMate - End to end testing is a critical piece to ensure quality and avoid...
GridMate - End to end testing is a critical piece to ensure quality and avoid...
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 

Lecture8 php page control by okello erick

  • 2. 2 Server Side Includes It is possible to insert the content of one PHP file into another PHP file with the include or require statement. The include and require statements are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will continue
  • 3. 3 Server Side Includes Syntax <?php require("header.htm"); ?> <?php include("footer.php");?>
  • 4. How to create variables storing values across php scripts’ calls? Client-server connection is not permanent => Cannot be saved in program memory There are many clients connecting simultaneously => Cannot be saved in file (you cannot identify clients as well sometimes) . . .
  • 5. Different mechanisms of the same solution  Cookies  Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.  Sessions  Session support in PHP consists of a way to preserve certain data across subsequent accesses. This enables you to build more customized applications and increase the appeal of your web site.
  • 6. What is a Cookie? A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests for a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
  • 7. How to Create a Cookie The setcookie() function is used to create cookies. Note: The setcookie() function must appear BEFORE the <html> tag. setcookie(name, [value], [expire], [path], [domain], [secure]); This sets a cookie named "uname" - that expires after ten hours. <?php setcookie("uname", $name, time()+36000); ?> <html> <body> …
  • 8. How to Retrieve a Cookie Value  To access a cookie you just refer to the cookie name as a variable or use $_COOKIE array  Tip: Use the isset() function to find out if a cookie has been set. <html> <body> <?php if (isset($uname)) echo "Welcome " . $uname . "!<br />"; else echo "You are not logged in!<br />"; ?> </body> </html>
  • 9. How to Delete a Cookie  It will expire or  Cookies must be deleted with the same parameters as they were set with. If the value argument is an empty string (""), and all other arguments match a previous call to setcookie, then the cookie with the specified name will be deleted from the remote client.
  • 10. What is a Session?  The session support allows you to register arbitrary numbers of variables to be preserved across requests.  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.
  • 11. How to Create a Session The session_start() function is used to create cookies. <?php session_start(); ?>
  • 12. How do ‘Sessions’ work?  They are based on assigning each user a unique number, or session id. Even for extremely heavy use sites, this number can for all practical purposes can be regarded as unique. e.g. 26fe536a534d3c7cde4297abb45e275 a
  • 13. How do ‘Sessions’ work?  This session id is stored in a cookie, or passed in the URL between pages while the user browses.  The data to be stored (e.g. name, log-in state, etc.) is stored securely server- side in a PHP superglobal, and referenced using the session id.
  • 14. Crucially, sessions are easy to implement as PHP does all the work!
  • 15. Starting/Resuming a Session 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.
  • 16. Starting/Resuming a Session session_start(); When doing anything with sessions, this is always called first!
  • 17. Storing Session Data  The $_SESSION superglobal array can be used to store any session data. e.g. $_SESSION[‘name’] = $name; $_SESSION[‘age’] = $age;
  • 18. Reading Session Data  Data is simply read back from the $_SESSION superglobal array. e.g. $name = $_SESSION[‘name’]; $age = $_SESSION[‘age’];
  • 19. Session Propagation  Sessions need to pass the session id between pages as a user browses to track the session.  It can do this in two ways:  Cookie propagation  URL propagation
  • 20. How to Retrieve a Session Value Register Session variable session_register('var1','var2',...); // will also create a session PS:Session variable will be created on using even if you will not register it! Use it <?php session_start(); if (!isset($_SESSION['count'])) $_SESSION['count'] = 0; else $_SESSION['count']++; ?>
  • 21. Delete a Session Value session_unregister(´varname´); How to destroy a session: session_destroy()
  • 22. Destroying a Session Often not required, but if we want to destroy a session: // clear all session variables $_SESSION = array(); // delete the session cookie if there is one if (isset($_COOKIE[session_name()])) { setcookie(session_name(),'',time()-42000,'/'); } // destroy session session_destroy(); // avoid reusing the SID by redirecting // back to the same page to regenerate session header('Location: '.$_SERVER['PHP_SELF']);
  • 23. Session Expiry  By default, PHP sessions expire:  after a certain length of inactivity (default 1440s), the PHP garbage collection processes deletes session variables. Important as most sessions will not be explicitly destroyed.  if propagated by cookies, default is to set a cookie that is destroyed when the browser is closed.  If URL propagated, session id is lost as soon as navigate away from the site.
  • 24. Long-term Sessions  Although it is possible to customize sessions so that they are maintained after the browser is closed, for most practical purposes PHP sessions can be regarded as short-term.  Long-term session data (e.g. ‘remember me’ boxes) is usually maintained by explicitly setting and retrieving cookie data.
  • 25. Using Cookies  Cookies are small pieces of data that a server sends to a browser for storage. When a browser contacts a server, it sends along any cookies for that server under the variable $_COOKIES. Similarly, a server can set one or more cookies on the browser for retrieval at a later time.
  • 26. The first part of program session-cookies.php illustrates the typical use of cookies, with these lines:  $today = date('l, F j, Y');  $timestamp = date('g:i A');  if (strcmp($_COOKIE[LAST_VISIT], "") == 0) {  $lasttime = "";  } else {  $lasttime = $_COOKIE[LAST_VISIT];  }  $LAST_VISIT = $today . " at " . $timestamp;  // set last_visit cookie with date/time, with expiration for 2 full weeks  setcookie ("LAST_VISIT", $LAST_VISIT, time() + 3600*24*14);   if ($_COOKIE[VISIT_NUMBER] == 0) {  $visitcount = 0;  } else {  $visitcount = $_COOKIE[VISIT_NUMBER];  }  // set visit_number cookie with count, with expiration for 2 full weeks  setcookie ("VISIT_NUMBER",1 + $visitcount, time() + 3600*24*14);
  • 27. additional notes:  Here are a few additional notes:  Cookies are sent with Web page headers, so any setting of cookies must take place BEFORE the DOCTYPE line in an HTML/PHP script.  PHP function setcookie specifies a cookie ID, a value, and a length of time for which the cookie will be kept by the browser.  PHP variable $_COOKIE is an associative array that maintains the list of cookies set previously.
  • 28. Check if your browser is usually set to accept cookies.  If you use the Mozilla browser, this information can be found by looking under "Preferences" in the "Edit" menu, and then going to "Privacy & Security" and "Cookies".  If you use the Iceweasel browser, this information can be found by looking under "Preferences" in the "Edit" menu, and then going to the "Privacy" tab.  If you use Internet Explorer under Windows, this information can be found by looking under select "Internet Options" from the "Tools" menu, then look under "General" and "Settings" in the "Temporary Internet Files" section.  If you use Internet Explorer on a Macintosh, this information can be found by looking under "Preferences" under the "Explorer" menu, and then looking under "Cookies" in the "Receiving Files" section.
  • 29. Session Variables  Effectively, session variables are cookies that remain active only while the browser is actively interacting with the server. When time elapses, or when you close your browser, the session variables disappear. (If cookies are not allowed by a user, then information for sessions may be placed in a query string at the end of a URL.)  The following lines from session-cookies- 2.php illustrate typically processing of session variables.
  • 30. The following lines illustrate typically processing of session variables.  // check if person has logged in previously  session_start();  $processingOK = "not yet";  $firstLogin = "no";  if (isset ($_SESSION['authorized'])) {  // user already logged in  $processingOK = $_SESSION['authorized'];  } else {  // user not logged in, so check password  $password = trim($_POST['password']);  if ($password == 'Test') {  // correct password given  $processingOK = 'ok';  $_SESSION['authorized'] = 'ok';  $firstLogin="yes";  } else {  // invalid password  }  }
  • 31. Here are some notes regarding session variables:  A script uses session_start() to initialize and register any session variables.  As with cookies, session variables are sent with Web page headers, so any setting of session information must take place before the DOCTYPE tag.  PHP variable $_SESSION is an associative array that maintains the list of session variables set previously.  PHP function isset determines whether a specific $_SESSION field has a designated value.  PHP function unset removes a session value that was sent previously, and session_unset() removes all session values.
  • 32.  <?php  // Note - cannot have any output before this  session_start();  if ( ! isset($_SESSION['value']) ) {  echo("<p>Session is empty</p>n");  $_SESSION['value'] = 0;  } else if ( $_SESSION['value'] < 3 ) {  $_SESSION['value'] = $_SESSION['value'] + 1;  echo("<p>Added one...</p>n");  } else {  session_destroy();  session_start();  echo("<p>Session Restarted</p>n");  }  ?>  <p><a href="sessfun.php">Click Me!</a></p>  <p>Our Session ID is: <?php echo(session_id()); ?></p>  <pre>  <?php print_r($_SESSION); ?>  </pre> http://www.php-intro.com/code/sessions/sessfun.php
  • 34. 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
  • 36. <?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: http://www.dr-chuck.com"); return; } } ?> <html> <body style="font-family: sans-serif;"> <p>I am Router Two...</p> <form method="post"> <p><label for="inp9">Where to go? (1-3)</label> <input type="text" name="where" id="inp9" size="5"></p> <input type="submit"/></form> </body> http://www.php-intro.com/code/sessions/redir1.php
  • 37. Approved  <?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;  }  ?>  <html>
  • 38. 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
  • 40. POST-Redirect-GET-Flash  POST detects error in input data and puts a message into $_SESSION and redirects  GET sees the message in the session, displays it and then deletes it  Flash = "Seen once"
  • 41. ?><html> <head></head> <body style="font-family: sans-serif;"> <h1>Please Log In</h1> <?php if ( isset($_SESSION["error"]) ) { echo('<p style="color:red">'. $_SESSION["error"]."</p>n"); unset($_SESSION["error"]); } if ( isset($_SESSION["success"]) ) { echo('<p style="color:green">'. $_SESSION["success"]."</p>n"); unset($_SESSION["success"]); } ?> <form method="post"> <p>Account: <input type="text" name="account" value=""></p> <p>Password: <input type="text" name="pw" value=""></p> <p><input type="submit" value="Log In"></p> </form> </body> login.php
  • 43. ?><html><head></head> <body style="font-family: sans-serif;"> <h1>Online Address Book</h1> <?php if ( isset($_SESSION["success"]) ) { echo('<p style="color:green">'.$_SESSION["success"]."</p>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'] : ''; http://www.php-intro.com/code/sessions/index.php
  • 44. if ( ! isset($_SESSION["account"]) ) { ?> Please <a href="login.php">Log In</a> to start. <?php } else { ?> <p>Please enter your address:<form method="post"> <p>Street: <input type="text" name="street" size="50" value="<?= echo(htmlentities($street) ?>"></p> <p>City: <input type="text" name="city" size="20" value="<?= echo(htmlentities($city) ?>"></p> <p>State: <input type="text" name="state" size="2" value="<?= echo(htmlentities($state) ?>"> Zip: <input type="text" name="zip" size="5" value="<?= echo(htmlentities($zip) ?>"></p> <p><input type="submit" value="Update"> <input type="button" value="Logout" onclick="location.href='logout.php'; return false"></p> </form> <?php } ?> </body> index.php
  • 45. <?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; } ?><html> index.php
  • 46. Exercise  Write a program called Web page session-cookies.php that tries to save a cookie to keep track of whether or not you have visited this page previously.