📖 PHP Sessions and Cookies
Creating Persistence
HTTP is a stateless protocol, which means that it does not keep connections open any longer than necessary. As soon as the web server sends a page to your browser, it terminates the connection. It does not keep track of users who are currently using the site. This makes the server much more efficient, but makes programming more difficult as you must then keep track of all information regarding a user's browser session yourself. Many companies program sites to keep the connection with the visitors more persistent to improve the user experience. Here are a few ways to do this.
- Hidden Form Fields
- You can hide data in a form using a hidden form field. The user doesn't see it, but the server has access to the value.
- Query string
- We have used the query string to pass information from one page to another, but this is done in full view of the user and anyone else who views the transmission - not acceptable for security information.
- Session Variables
- Creates a file on the server to store information about the user and creates a cookie on the user's computer with a sessionID that relates to that file. Sessions are temporary. They usually only last 10 - 20 minutes ans have to be continuously refreshed to keep them active.
- Cookies
- Information stored on the user's computer to retain information across transmissions to the server. This is effective at extending a personalized interaction with users over long periods of time.
Sessions
To use session variables in PHP, you must explicitly start the session by putting the following code as the very first line of the PHP file or you must buffer the output prior to creating the session.
<?php session_start(); ?>
The server will create a new session with a session id. The session id is stored as a cookie on the user's computer to keep track of the session. Session data is stored on the server and will be deleted at the end of the session. The session ends when the session is specifically destroyed or when the user has not returned to the server for a specified amount of time (specified in the php.ini file).
Session data is stored in a superglobal array called $_SESSION[ ]. To access a specific element, use $_SESSION["elementName"]
. For example, if you wanted to retrieve a session variable called userName, you would code this way.
$userName = $_SESSION["userName"];
To create or store a value in a session variable, code $_SESSION["elementName"] = value;
For example, to create a userName session variable from a form field, you would code this way.
$_SESSION["userName"] = $_POST['userName'];
Setting Session Variables at Login
Often developers will use this as part of a login script that takes the user's login credentials and looks them up in a database. This is called user authentication. If they match an existing record that record is returned to the script at which time the script assigns certain personal attributes from the database user record to session variables for use during the user's current session. User's must be active to keep a session going as most sessions will time out in 10 - 20 minutes.
Example
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT `memberID`, `firstname`, `lastname` FROM `membership` WHERE `username` = $username AND `password` = $password;";
// run query and return matching record
$result = mysqli_query($conn,$query);
if (!$result) {
die(mysqli_error($conn));
}
if ($row = mysqli_fetch_assoc($result)) {
// set the database field values to session variables for futher use in the script
$_SESSION['memberID'] = $row['memberID'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['lastname'] = $row['lastname'];
} else {
echo "Sorry, we could not find you in the system.";
}
}
// login is also a good time to set a cookie for the user's name, if you want to provide an extended greetings
To find out if a session variable has a value, use the isset()
function:
if (isset($_SESSION['userName'])) {
print "Hello " . $_SESSION['userName'];
} else {
print "Hello Guest";
}
To destroy a session variable use the unset()
function.
if ($_POST['clearCart'] = = "yes") {
unset($_SESSION['cart']);
}
To destroy all session variables use unset($_SESSION);
To end the session and remove all the session variables from the server use session_destroy();
Destroying Sessions at Logout
Logout scripts often take care to destroy sessions and all session elements. Place this script in your index.php page and create a Logout button that is available on every page for users to easily find. Have the button load the index.php page with a hidden field named logout. This will trigger the logout script to unset the session variables and destroy the session.
Example
if (isset($_POST['logout'])) {
$msg = 'You are Logged out.';
foreach ($_SESSION as $field => $value){
unset($_SESSION[$field]);
}
session_destroy();
header("Location: index.php?msg=$msg");
exit;
}
Use session variables with caution if you have a large number of users as they can use a lot of space on the server. Some times it's better to use cookies for basic personalization features and only use sessions for more secure authentication. For example, if I want to greet visitors by name each time they visit my site, I would use cookies. Users don't have to login for cookies to work. However, if a registered user wanted to update their profile or make a purchase, I would have them go through the login process to authenticate their access to these areas of the site.
Cookies
Cookies are stored on the user's computer in a special area associated with the browser where only the application that created the cookie can read the cookie. Cookies must be sent from the server to the client prior to sending any HTML so the PHP code must come before any HTML or you must buffer the HTML.
Create a Cookie
Format
setcookie(name, value [, expire, path, domain, secure, httponly]);
The cookie parameters in brackets[ ] above are optional.
- name
- The name you give the cookie. (required)
- value
- The value assigned to the cookie. (required)
- expire
- The time when the cookie will cease to exist. (optional)
- It is usually set by adding seconds to the current time.
- time()+3600 would expire in one hour (3600 seconds from now).
- time()+ (60 * 60 * 24 * 30) would expire in a month (60 seconds * 60 minutes * 24 hours * 30 days).
- If not specified, it will expire at the end of the browser session.
- path and domain
- Limits the cookie to a specific folder (path) or subdomain. (optional)
- Setting the path to "/" makes the cookie accessible to the entire website.
- secure
- Indicates whether a secure connection must be used. 1 requires a secure connection and 0 does not (default). (optional)
- httponly
- Restricts access to the cookie, but isn't supported by all browsers. (optional)
Example
Most of the time, only the name
, value
and expire
parameters are used.
setcookie('firstname', 'Mary', time()+ 60*60*24*30);
// sets the firstname cookie to 'Mary' for 30 days
Read a Cookie
Format
/* use the $_COOKIE[] superglobal array. */
$variableName = $_COOKIE['cookieName'];
// cookieName is the name assigned the cookie in the setcookie() function
// this will assign the value of the specified cookie to $variableName
Use isset( $_COOKIE['cookieName'])
to see if a cookie exists.
Example
if(isset($_COOKIE['firstname'])){
$firstname = $_COOKIE['firstname'];
} else {
$firstname = 'Guest';
}
echo "<p>Welcome back, $firstname.</p>";
Cookies are not available immediately after they have been set.
To manually delete a cookie, set the value of the cookie to a null string or to FALSE. You can also set the expiration to the past.
setcookie(name, "", time()-600 [, path, domain, secure, httponly]);
orsetcookie(name, FALSE, time()-600 [, path, domain, secure, httponly]);
- If path, domain, secure or httponly were used when the cookie was set, then you must use the same values for those parameters when you delete the cookie.
- Cookies will be automatically deleted when the expiration time is reached.