Professional Documents
Culture Documents
PHP Programming
By
1
Brwa Jalal Kurdistan Technical Institute(www.kti.edu.krd/ku) - CS Department .
Previous Lecture
ØForm Validation
Overview
ØPHP - Cookies
ØPHP - Sessions
PHP - Cookies
Ø A cookie is a small text file that lets you store a small amount of data
(nearly 4KB) on the user's computer.
Ø They are typically used to keeping track of information such as username
that the site can retrieve to personalize the page when user visit the
website next time.
Ø You can use the print_r() function like print_r($_COOKIE); to see the
structure of this $_COOKIE associative array, like you with other arrays.
Deleting Cookie with PHP
Ø You can delete a cookie by calling the same setcookie() function with the
cookie name and any value (such as an empty string)
Ø Officially, to delete a cookie you should call setcookie() with the name
argument only but this does not always work well, however, and should not
be relied on.
Ø It is safest to set
the cookie
with a date that has
already expired
What is a Session in PHP
Ø Although you can store data using cookies but it has some security
issues.
Ø Since cookies are stored on user's computer it is possible for an attacker
to easily modify a cookie content to insert potentially harmful data in your
application that might break your application.
Ø You can solve both of these issues by using the PHP session.
Ø A PHP session stores data on the server rather than user's computer.
Ø In a session based environment, every user is identified through a unique
number called session identifier or SID.
Ø This unique session ID is used to link each user with their own
information on the server like emails, posts, etc.
Starting a PHP Session
Ø Before you can store any information in session variables, you must first
start up the session.
Ø To begin a new session, simply call the session_start() function.
Ø It will create a new session and generate a unique session ID for the
user.
Ø The PHP code in the example below simply starts a new session.
<?php
// Starting session
session_start();
?>
Ø The session_start() function first checks for an existing session ID.
Ø if the session is already started, it sets up the session variables and if
doesn't, it starts a new session by creating a new session ID.
Storing and Accessing Session Data
Ø Note: To access the session data in the same page there is no need to
recreate the session since it has been already started on the top of the
page.
Destroying a Session