Topic 9 CIS423 PHP Sessions Cookies

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

College of Computer Science & IT

CIS 423:Web-based Systems

PHP
Sessions &
Cookies
+
Encrypting Passwords stored in DB

◼ Using password(); function to encrypt the password before


storing it in the database.

◼ There are number of encryption functions that you can use.


+ Redirecting the browser using
header() function
Using header (location: );
◼ the header( ) function will be used to redirect the Web browser
from the current page to another.
header(header string);

◼ Examples:
◼ header ('Location: http://www. example.com/page.php');
◼ header("Content-Type:application/ pdf\n");
header ("Content-Disposition: ➝ attachment;
filename=\"somefile.pdf\"\n");

◼ After redirecting the current browser to another page, you need


stop the current running script by using either exit() or die()
functions.
◼ But what is the difference between exit() or die() functions?
+
die(); vs. exit;

◼ The same!
+
Interacting with the File System
and the Server
◼ dirname() Function:

◼ Retreive the name of the current directory using


the dirname( ) function, in case the redirection is taking
place within a subfolder.

◼ Using the superglobar $_SERVER[]


◼ Retrieves the name of the server you want to redirect to by using:
$_SERVER['HTTP_HOST’].
◼ This superglobal variable $_SERVER with the parameter
['HTTP_HOST’]will retrieve either localhost or www.
example.com
+
Use Dynamic Coding
Instead of hard coding (as much as you can to avoid
errors)

◼ If you want to redirect the browser of the user to another


URL using any method [e.g header ( Location: $URL)]:
◼ Where $url = 'http://' . $_SERVER ['HTTP_HOST'] .
dirname($_SERVER ['PHP_SELF']);
◼ This superglobal variable $_SERVER with the parameter
[’PHP_SELF’]will refers to the current script (which will be the one
calling this function)
◼ Also add to it any sub-directories or the name of certain pages you
want the user to go to.
◼ Example : Script 12.2
+
The
Login
Process
&
Sessions
+
The Login Process

◼A form for submitting the login information


◼A validation routine that confirms the necessary
information was submitted
◼A database query that compares the submitted
information against the stored information
◼ Cookiesor sessions to store data that reflects a
successful login
+
Making the Login Functions

◼ Afterthe user logs in, the user should be


redirected using the header() function [PHP &
MySQL for Dynamic Web:Chapter#11]
◼ Also, after the header() function is called the
exit(); function should be called.
◼ Ifyou don’t call exit( ), the current script will
continue to run ( just not in the Web browser).
+

Sessions
+
What is a Session?

◼ The premise of a session is that data is stored on the


server, not in the Web browser, and a session identifier
is used to locate a particular user’s record
◼A Sessions is a super global variable $_SESSION (an
array).
◼ Youcan refer to any element in the array by using
$_SESSION[‘KeyValue’].
◼ Sessions
values are saved on the server [using php],
whereas the browser cookies are saved on your
computer(in your browser)[using php or JavaScript].
+
What is a Session? (cont’d)

◼ Itwill start having a value by calling the function


Session_start();
◼ Session_start(); must be called at the beginning of each page you
want to maintain the session values stored and held by the server.
◼ After that, you must begin a session. This is required for the
shopping cart functionality to work. Every page in the site will use
the session.
◼ As long as the browser is connected to that server, the session
values will travel within the site.
+
Creating & Accessing Session
Values
◼ Example: ($_SESSION['key'] = value; )
session_start( );
$_SESSION[’first_name'] = ’Ali';
$_SESSION[’user_id'] = 48;

if (isset($_SESSION['user_id']))
{ echo "<h1>Logged In!</h1>
<p>You are now logged in, {$_SESSION['first_name']}!</p>
<p><a href=\"logout.php\">Logout </a></p>"; }

Example : Script 12.9


+
What is a Session? (cont’d)

◼ The first time this function is used, session_ start():


◼ will attempt to send a cookie with a name of PHPSESSID (the
default session name) and a value of something like
a61f8670baa8e90a30c878df89a2074b (32 hexadecimal letters,
the session ID).
◼ Because of this attempt to send a cookie, session_start()
must be called before any data is sent to the Web browser, as
is the case when using the setcookie() and header()
functions.

◼ To
remove the session variable value:
unset($_SESSION[‘KeyValue’]);
◼ Or session_destroy()
+
Cookies
How cookies are sent back and forth
between the server and the client.
+
What are 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 the client during and
between browsing sessions.
◼A server can access only his own created cookies.
◼ Used for:
◼ Saving user’s preferences.
◼ Tracking user’s activity.
◼ Store any type of information required for future services
or anything similar.
+
Cookies

◼ The most important thing to understand about cookies is that


they must be sent from the server to the client prior to any
other information.
◼ Should the server attempt to send a cookie after the Web browser
has already received HTML—even an extraneous white space—an
error message will result and the cookie will not be sent .

◼ Cookies are sent via the setcookie( ) function:


setcookie (name, value); setcookie ('name', 'Nicole');

◼ The setcookie( ) function is one of the few functions in PHP


that could have different results in different browsers, since
each browser treats cookies in its own way
+
Accessing cookies

◼ To retrieve a value from a cookie, you only need to refer to the


$_COOKIE superglobal, using the appropriate cookie name as
the key (as you would with any array).

◼ For example, to retrieve the value of the cookie established with the
line:
◼ setcookie ('username', ’Ahmed');
◼ Check for the presence of a cookie:if (isset($_COOKIE['user_id']))
◼ Then you would refer to $_COOKIE['username'].

◼ Example: Script 12.3 login.php & Example 19.10 (Deitel & Deitel)

◼ What do you think about storing a cookie with $data['user_id'] or


password on a client side?
+
Setting Cookie Parameters

◼ setcookie (name, value, expiration, path, host,


secure, httponly);
◼ Expiration: The expiration argument is used to set a
definitive length of time for a cookie to exist,
specified in seconds. (known by Persistent Cookie)
◼ If it is not set or if it’s set to a value of 0, the cookie
will continue to be functional until the user closes
their browser (known by Session Cookie)
◼ Example: setcookie (name, value, time()+1800);
when will this cookie expire?
+
Setting Cookie Parameters

◼ setcookie (name, value, expiration, path, host, secure,


httponly);
◼ Path: The path and host arguments are used to limit a cookie to a specific
folder within a Web site (the path) or to a specific host (www. example.com
or 192.168.0.1).
◼ For example, you could restrict a cookie to exist only while a user is within
the admin folder of a domain (and the admin folder’s subfolders):
◼ Setting the path to / will make the cookie visible within an entire domain
(Web site).
◼ Example setcookie (name, value, expire, '/admin/’);
where will this cookie be saved?
+
Setting Cookie Parameters

◼ setcookie (name, value, expiration, path, host, secure,


httponly);
◼ Secure: The secure value dictates that a cookie should only be sent over a
secure HTTPS connection.
◼ A 1 indicates that a secure connection must be used, and a 0 says that a
standard connection is fine.
◼ Httponly: A Boolean value is used to make the cookie only accessible through
HTTP (and HTTPS).
◼ Enforcing this restriction will make the cookie more secure (preventing
some hack attempts) but is not supported by all browsers at the time of this
writin

◼ To skip any parameter, use NULL, 0, or an empty string (don’t use


FALSE).
◼ Although the setcookie( ) function can take up to seven arguments, only one
is actually required
+
Deleting Cookies

◼ While a cookie will automatically expire when


the user’s browser is closed or when the expiration
date/time is met, often you’ll want to manually delete
the cookie instead.
◼ setcookie (’Name', '', time()-3600, '/', '', 0, 0);
◼ Exceptfor the value and the expiration, the other
arguments should have the same values as they do
when the cookies were created.
◼ Example : Script 12.7
+
Cookies (Testing Cookie-Handling)
◼ Differentversions of different browsers on different
platforms all define their cookie-handling policies
in different places.

◼ To
effectively program using cookies, you need to
be able to accurately test for their presence.
◼ The best way to do so is to have your Web browser ask what
to do when receiving a cookie. In such a case, the browser
will prompt you with the cookie information each time PHP
attempts to send a cookie
+
Cookies (Testing Cookie-Handling
cont’d)
◼ To set this up using Internet Explorer on Windows: IE ➔ Tools ➔
Internet Options ➔ Privacy tab ➔ the Advanced button under
Settings ➔ Click “Override automatic cookie handling” ➔then
choose “Prompt” for First-party Cookies.
+
Cookies (Testing Cookie-Handling
cont’d)
◼ Using Firefox on
Windows: choose
Tools ➔ Options ➔
Privacy. Firefox on
Mac OS X: Firefox ➔
Preferences ➔
Privacy tab, ➔ select
“Use custom settings
for history” and
you’ll see the “Keep
until” selector.
+
Setting Google Chrome Cookies
+
Cookies vs. Sessions: What is the
main difference between them?
Sessions Cookies
◼ They are generally more ◼ They are easier to
secure (because the data program.
is being retained on the
server).
◼ They require less of the
◼ They allow for more data server.
to be stored.
◼ They can be made to last
◼ They can be used far longer.
without cookies
In general, to store and retrieve just a couple of small pieces of
information, or to store information for a longer duration, use
cookies. For most of your Web applications, though, you’ll use
sessions.
+

Questions?
+ To test the session scripts
◼ Create a folder and name it session

◼ Add the following scrpits to it

◼ Login.php script 12.8

◼ Loggedin.php script 12.9

◼ Logout.php script 12.11

◼ Add the Script 3.4 - index.php (add the code session_start() to the
beginning of the script).

◼ add folder includes from ch12, then replace header.html with Script
12.10 - header.html

◼ Add to the includes folder both login_functions.inc.php 12.2 and


login_page.inc.php scripts 12.1 both under the ch12 folder directlly

◼ add Script 9.2 - mysqli_connect.php place it under the htdocs folder,


add the user username and password password to phpmyadmin.

◼ add the sql file sql.sql to upload the database.


+
References

◼ Steps to create a layout:


◼ http://www.php.net/manual/en/function.header.php
◼ http://www.w3schools.com/php/func_http_header.asp
◼ http://www.php.net/exit
◼ http://www.php.net/die
◼ PHP Login Sessions:
◼ http://www.youtube.com/watch?v=YouZ67vfccA
◼ https://www.youtube.com/watch?v=PXugYdXCBck&ab_channe
l=OnlineITtutsTutorials

You might also like