Professional Documents
Culture Documents
Introduction
Session Control
PHP Cookies
PHP Sessions
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
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
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
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
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
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
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
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??
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
Syntax:
session start()
Registering a session:
$ SESSION[’username’] = "john";
$ SESSION[’password’] = $ POST["passwordd"];
SESSION
output
CONT…
When next page clicked, page2.php will be opened
Example
Output
CONT …
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
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
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);
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
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
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..