You are on page 1of 65

CHAPTER SEVEN

Cookies and Session Management in PHP

Prepared by: Marta G. (MSc. )


CONTENT

 Introduction
 Session Control

 Why Should We Care?

 PHP Cookies

 PHP Sessions

 Why We Use Sessions at All When Cookies Work Just Fine?


INTRODUCTION

 As web applications have matured, the need for statefulness has become a common
requirement
 Stateful web applications:
 Applications that keep track of a particular visitor’s information as he travels throughout a site

 HTTP is a stateless protocol, and each HTML page is an unrelated entity


 HTTP has no built-in way of maintaining state between two transactions
 HTTP remembers nothing about previous transfers
 It means: when a user requests one page, followed by another page,
 The HTTP protocol itself does not provide a way for you to tell that both requests came from the same
user
INTRODUCTION

 Without the server being able to track a user, there can be no shopping carts or
custom website personalization
 Using a server-side technology like PHP, you can overcome the statelessness of the
web
 The two best PHP tools for this purpose are cookies and sessions

 The key difference between cookies and sessions is that:


 Cookies store data in the user’s browser
 Sessions store data on the server itself
 Sessions are generally more secure than cookies and can store much more
information
INTRODUCTION

Why Should We Care?


 We want to customize our users’ experiences as they move through the site, in a way
that depends on which (or how many) pages they have already seen
 We want to display advertisements to the user, but we do not want to display a
given ad more than once per session
 We want the session to accumulate information about users’ actions as they progress
 We are interested in tracking how people navigate through our site in general
COOKIES
 Technically, cookies are arbitrary pieces of data chosen by the Web server and sent
to the browser.
 The browser returns them unchanged to the server, introducing a state (memory of
previous events) into otherwise stateless HTTP transactions.
 Without cookies, each retrieval of a Web page or component of a Web page is an
isolated event, mostly unrelated to all other views of the pages of the same site.
 Cookies can also be thought of as tickets used to identify clients and their orders

 A cookie is a small packet of information stored on the browser, and it is


persistent, meaning
 Itis maintained between browser sessions and might persist even when the user shuts down
his or her computer
CONT…

 Cookies, or browser cookies, are small pieces of data (maximum of 4KB)


which the web server asks the client’s web browser to store
 Each request back to the web server will include pieces of data
 The data is organized as key/value pairs

 It contains information about the viewer that can be retrieved and used at
a later time
 The information is passed back and forth between the server and browser
via HTTP headers
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
 If the server attempt to send a cookie after the browser has already
received HTML - even an extraneous white space
 An error message will result and the cookie will not be sent
COOKIES

Attributes
 Name: the actual cookie text consists of the name of the cookie

 Value: the value you want to store in the cookie


 If this argument is not supplied, the cookie named by the first argument is
deleted
 Expiration Date: the time where the cookie expires

 Domain Name: specifies a general domain name to which the cookie should apply

 Path: used to specify where the cookie is valid for a particular server

 Security: If a cookie is secure, it must be sent over a secure

communication channel (HTTPS server)


COOKIES

Creating Cookies
 A cookie is created with the PHP built-in setcookie() function, which takes at least
one argument, the name of the cookie
 Syntax:
 Note: The setcookie() function must appear before the <html> tag
 The second argument is the value that will be stored in the cookie such as a
username, date, email, and so on
 Itis not a good idea to put any kind of sensitive personal information in cookie files because
cookie files are readable text files
 Other optional arguments include the expiration date of the cookie, and the path
where the cookie is valid, and lastly, whether or not to make the cookie secure
 Ifyou do not set the expiration date, the cookie will be removed when the browser session
ends
COOKIES

Creating Cookies
 Example

 Output
COOKIES

Viewing Cookie in Google Chrome Developer Tools


 Cookie information is normally located under an \Application“ or \Network"
section

 Right click on web page inspect  application  cookies


COOKIES

Guideline on Setting Cookie Expiration


 Some general guidelines for cookie expirations:
 If the cookie should last as long as the user’s session, do not set an expiration time
 If the cookie should continue to exist after the user has closed and reopened his or
her browser, set an expiration time weeks or months ahead
 If the cookie can constitute a security risk, set an expiration time of an hour or
fraction thereof
 So that the cookie does not continue to exist too long after a user has left his or her browser
 You could set a 5- or 10-minute expiration time on a cookie and have the cookie re-sent with

every new page the user visits (assuming that the cookie exists)
 This way, the cookie will continue to persist as long as the user is active but will automatically

die 5 or 10 minutes after the user’s last action


COOKIES

How to Retrieve a cookie value?


 The cookies are stored in the PHP global $_COOKIE array

 When a cookie is set, PHP assigns it to the global $_COOKIE associative array

 $_COOKIE array will contain all the cookie values saved for that page
COOKIES
Deleting a cookie
 Although 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
 For example, in web sites that have login capabilities, you will want to delete any cookies when the
user logs out
 When cookies are created, they are, by default, deleted when the user closes his or her
browser
 One way to delete a cookie is to set an expiration date that’s in the past or:
 Simply subtract from the current time to some earlier date
 Syntax:
 setcookie("cookie name", "", time() - 1);
 The second way is to send a cookie that consists of a name without a value
COOKIES
Deleting a cookie
 When deleting a cookie, you should always use the same parameters that set the cookie
(aside from the value and expiration, naturally)
 If you set the host and path in the creation cookie, use them again in the deletion cookie
 Remember that the deletion of a cookie does not take effect until the page has been
reloaded or another page has been accessed
 In other words, the cookie will still be available to a page after that page has deleted it
COOKIE

Deleting a cookie
 we can also use the isset() function to find out if a cookie has been set

Example:

 output
INTRODUCTION

Session Control
 Sessions are focused on maintaining visitor-specific state between requests
 The idea of session control is to be able to track a user during a single session on a
website
 PHP includes a rich set of native session control functions, as well as a single
$_SESSION superglobal variable for your use
SESSION

What is a session?
 A session is a way to store information (in variables) to be used across
multiple pages
 Unlike a cookie, the information is not stored on the users computer

 A session is the time that a user spends at a web site

 PHP provides us with a mechanism to manage sessions so that we can keep


track of:
 What a visitor is doing
 What he or she likes
 What he or she wants even after the user logs off

 Like cookies, the idea is to maintain state


SESSION
What is a session?
 When you work with an application, you open it, do some changes, and then you
close it
 This is much like a Session
 The computer knows who you are
 It knows when you start the application and when you end

 However, there is one problem on the internet


 The web server does not know who you are or what you do, because the HTTP doesn’t
maintain state
 Session variables solve this problem by storing user information to be used across
multiple pages (e.g. username, favorite color, etc)
 By default, session variables last until the user closes the browser
CONT….

 Session variables hold information about one single user, and are available to all
pages in one application
 Note: If you need a permanent storage, you may want to store the data in a database
 The session filename contains the unique ID number for the session
 The next time the visitor asks for the page, his or her browser sends the ID
number back to the server
 The server uses the session ID number to locate the file with the name that
corresponds to the same session ID number
CONT …
 The session file contains the actual session data
 For example, username, preferences, or items in the shopping cart
- information about the visitor that was stored the last time he or she visited the
page
 If this is the first time the user has visited the page, his or her preferences will be
collected and stored into the session file, to be retrieved later on
 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
CONT…
 The premise of a session is that data is stored on the server, not in the browser, and
 A session identifier is used to locate a particular user’s record (i.e., the session
data)
 This session identifier is normally stored in the user’s browser via a cookie, but the
sensitive data itself|like the user’s ID, name, and so on|always remains on the
server
 Why we use sessions at all when cookies work just fine?
WHY SESSION??

Why we use sessions at all when cookies work just fine?

1. Sessions are likely more secure in that all of the recorded information is stored on the
server and not continually sent back and forth between the server and the client

2. You can store more data in a session

3. Some users reject cookies or turn them off completely


 Sessions, while designed to work with a cookie, can function without them, too
SESSION

Setting Session Variables


 The most important rule with respect to sessions is that each page that
will use them must begin by calling the session start() function
 This function tells PHP to either begin a new session or access an existing one
 This function must be called before anything is sent to the browser
 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
 Value of something like 61f8670baa8e90a30c878df89a2074b (the session ID)
 Because of this attempt to send a cookie, session start() must be called
before any data is sent to the browser, as is the case when using the
setcookie() and header() functions
CONT…

Starting or Establishing a Session


 Typically session start() is called on top of the page, and then session variables
are registered in the superglobal $_SESSION array
 The session start() function creates a session or resumes one that has already started

 Syntax:
 session start()
 Registering a session:
$ SESSION[’username’] = "john";
 $ SESSION[’password’] = $ POST["passwordd"];
SESSION

Starting or Establishing a Session


Example:

output
CONT…
 When next page clicked, page2.php will be opened
 Example

 Output
CONT …

 When next page clicked, page3.php will be opened


 Example

 First output when we reload it


DESTROYING A SESSION

 If you wish to delete some session data, you can use the unset() or the session_destroy()
function
 To delete an individual session variable, use the unset() function
 unset($ SESSION[’var’])
 But to delete every session variable, you shouldn’t use unset()
 Instead, reset the $ SESSION array: $ SESSION = []
 Finally, to remove all the session data from the server, call session destroy() function
 Note: session destroy() will reset your session and you will lose all your stored session
data
 Note: prior to using any of these methods, the page must begin with session start() so
that the existing session is accessed
CONT…
 Example: create a simple page views counter
 The isset() function checks if the "views" variable has already been set

 If "views" has been set, we can increment our counter

 If "views" doesn’t exist, we create a "views" variable, and set it to 1


 If this page is viewed 32 times, the output is look like this
1. Explain in detail the difference between using cookies and using sessions
2. Does session control violate privacy of users?
CHAPTER EIGHT
PHP FILE MANAGEMENT
OUTLINE
 PHP File
 Opening and Closing Files

 Reading and Writing a File

 PHP File Uploading


PHP INCLUDE FILE
 PHP file can be inserted into another PHP file before the server executes it, with the
include() or require() function
 These functions are identical in every way except their error handling way
 include() generates a warning, but the script will continue execution
 require() generates a fatal error, and the script will stop

 They are used to create headers, footers, or elements that will be reused on multiple
pages
 You can create a standard header, footer, or menu file for all your web pages
 It saves a lot of work

 When the header needs an update, you can only update the include file, or
 When you add a new page to your site, you can simply change the menu file (instead of
updating the links on all your web pages)
PHP FILE UPLOAD
 Allowing a user to upload files from a form can be very useful

 The enctype attribute of the <form> tag specifies which content-type to use
when submitting the form
PHP FILE UPLOAD

 By using the super global PHP $_FILES array you can upload files from a client computer to the
remote server
 The first parameter is the form’s input name and the second index can be either "name", "type",
"size", "tmp_name" or "error"
 $ FILES["file"]["name"]: the name of the uploaded file
 $ FILES["file"]["type"]: the type of the uploaded file
 $ FILES["file"]["size"]: the size in bytes of the uploaded file
 $ FILES["file"]["tmp_name"]: the name of the temporary copy of the file stored on the server
 $ FILES["file"]["error"]: the error code resulting from the file upload
 Upload.php script
PHP FILE UPLOAD: RESTRICTIONS

 We can add some restrictions to the file upload


 The user may only upload:
 .png or .jpg files and
 The file size must be under 20kb
PHP FILE UPLOAD: SAVING THE UPLOADED FILE
 The examples above create a temporary copy of the uploaded files in the PHP temp folder
on the server
 The temporary copied files disappears when the script ends
 To store the uploaded file we need to copy it to a different location
 Code:
 Svupload.php output on web
browser

Out on file explorer


PHP FILE HANDLING: OPENING A FILE
 The fopen() function is used to open files in PHP
 The first parameter of this function contains the name of the file to be opened
and the second parameter specifies in which mode the file should be opened
PHP FILE HANDLING: OPENING A FILE
 Additional Useful File Functions
 fclose(): closes a file or URL Eg.fclose(fh)
 feof (): tests for end-of-file Eg. feof(fh)
 fgetc(): gets a character from a file. Eg. fgetc(fh)
 fgets(): gets a line from a file Eg. fgets(fh)

Opening a File for Reading


 Before opening a file you need to determine whether or not the file exists
and is accessible for reading
 The file exists() function checks to see if the file exists, and the
 is_readable() function will return true if a file exists and has read permission
 Four PHP functions are used for reading text from a file:
 fgets(), fgetc(), fread(), and file get contents()
PHP FILE HANDLING: OPENING A FILE
PHP FILE HANDLING: OPENING A FILE
Checking End-of-File
 The feof() function checks if the "end-of file" (EOF) has been reached

 The feof() function is useful for looping through data of unknown length
 Note: You cannot read from files opened in w, a, and x mode
Reading a File Line by Line
 The fgets() function is used to read a single line from a file
 Note: after a call to this function the file pointer moves to the next line
Reading a File Character by Character
 The fgetc() function is used to read a single character from a file
 Note: after a call to this function the file pointer moves to the next character
PHP FILE HANDLING: OPENING A FILE
fread()
 fread() function takes a filehandle and length as its argument and return a specified
number of characters
 Format:
 $file = fopen("filename", "r");
 $contents = fread($file, 5);

Reading from Files Without a Filehandle


 PHP provides functions that allow you to read the contents of a file without first
opening a filehandle
 file_get_contents(): reads and returns entire file in a string
 Format:
file_get_contents("text.txt")
OPENING A FILE FOR WRITING AND APPENDING

For Writing
 The fwrite() function writes a string text to a file
 It takes three arguments:
 The filehandle returned by fopen()
 A string that will write to the file

 An optional length argument (how many bytes to write to the file)

 Format:
 fwrite(filehandle, string, [int length])
OPENING A FILE FOR WRITING AND APPENDING
CONT…
OPENING A FILE FOR WRITING AND APPENDING CONT...
 The file_put_contents() function: writes a string to a file and returns the number of
bytes written, but does not require a filehandle
 Otherwise it is the same as fwrite() and fputs()
For Appending
 When a file is opened for appending, the write will start at the end of the file
 If the file does not exist, it will be created
FILE CHECKS

 Before performing operations on files or directories, it is a good practice to verify:


 Whether or not the file even exists
 If it is readable, writable, executable, and so on

 PHP provides a set of functions for testing the status of a file


 file exists():
 Checks if the file or directory exists
 It returns TRUE if it does, and FALSE if it does not

 is_dir(): checks if the filename is a directory


 is_file():
 Checks if the filename is a file
 It takes the name of the file as its argument
 Returns TRUE if the file is a regular file, and FALSE if it is not
 Format: is_file(string filename)
FILE CHECKS CONT…

 is_readable(): checks if the file is readable


 It takes the filename as its argument and returns TRUE if the filename exists
and is readable
 Format: is readable(string filename)
CREATING, COPYING, RENAMING, AND DELETING FILES

 copy(): return true if the file was correctly copied, or false if there was
an error
 To copy a file, you will need write permission on the directory where the new
copy will be stored
 Format: copy(string source file, string destination file)
 Code:
 Output on the file explorer:
CREATING, COPYING, RENAMING, AND DELETING FILES CONT..

 The rename() function: is used to give a file or directory another name


It returns true on success, and false if it fails
Format: rename(string old file,string new file)
Example: rename(\testw.txt", \testwr.txt")

 The unlink() function: is used to remove a file


It returns true if it can remove the file and false if not
Format: unlink(string filename)
unlink("text.txt")
DIRECTORIES
 PHP supports a number of functions to allow you to work with directories in the file
system
 From a PHP script, you can:
 Open a directory and read its contents,
 Change to a new directory
 List the current working directory
 Remove a directory, and so on

 chdir(): changes the directory


 chroot(): changes the root directory

 closedir(): closes a directory


 Handle previously opened with opendir()
 getcwd(): gets the current working directory
DIRECTORIES CONT…
 The opendir() function: is used to open a directory, similar to the fopen() function for opening files
 When you open a directory with the opendir() function, you create a directory handle to allow
access to the directory as it is stored on the disk by the operating system regardless of its internal
structure
 Once it is opened, you can access the directory with the PHP functions
 Returns a directory handle that can be used with readdir(),closedir()
 If the directory cannot be opened, false will be returned

 Format: opendir(string path)


 Example: // $dirhandle is a resource similar to a filehandle
 $dirhandle = opendir("/images")
DIRECTORIES CONT…
 The readdir() function: reads the next file from a directory handle opened
with opendir()
 A directory can be read by anyone who has read permission on the directory
 When we speak of reading a directory, we are talking about looking at its contents
with the readdir() function
 readdir(): reads an entry from a directory handle, given as its argument, and returns
the name of a file from the directory
 Format: readdir(resource dir handle)
 Example: $dirhandle=opendir("/images")

// Gets one file from the directory


// Use a loop to get them all
one file = readdir($dirhandle)
DIRECTORIES CONT…

 rmdir(): deletes a directory


 It must be empty and have write permission

 scandir(): returns an array of files and directories from a given path


 unlink(): deletes a file from a directory
DIRECTORIES CONT…
 Code :
 Output
THANK YOU!

You might also like