Cookies, or browser cookies, are small pieces of data which the web server asks the client's web browser to store. Each request back to the server will include these pieces of data. The data is organized as key/value pairs.
A cookie can be set using PHP's
<?php setcookie('language', 'english'); ?>
On future requests, the cookie key/value pairs will assigned to the
<?php echo $_COOKIE['language']; // english ?>
In addition to the
setcookie() also accepts many other arguments for configuration.
<?php $name = 'language'; $value = 'english'; $expire = time() + 60*60*24*3; // 3 days from now $path = '/blog'; $domain = 'www.mysite.com'; $secure = isset($_SERVER['HTTPS']); // or use true/false $httponly = true; setcookie($name, $value, $expire, $path, $domain, $secure, $httponly); ?>
Many of these configuration arguments are important for preventing attacks such as Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF), Cookie Theft and Manipulation, Session Hijacking, and Session Fixation.
Sessions are an alternative to cookies. A session is usually a file or database record on the server side which contains the small pieces of data which the server wants to store for each user. Instead of sending key/value pairs to the browser, these values are stored on the server, and only a reference identifier ("session ID") is sent to the user's browser as a cookie. This session ID needs to be a long and unique string. On each future request, the browser will send the session ID as a cookie and the server will locate the corresponding session to allow access to the stored user data.
In PHP it is important to always initialize sessions using
session_start(). After being initialized, session values can be set and retrieved using the
<?php session_start(); $_SESSION['user_id'] = 42; echo $_SESSION['user_id']; // 42 ?>
A session can also be unset and destroyed when expired or no longer needed. If not unset/destroyed, then the session file and session data will remain on the server unless the file or database storage for the session is deleted.
<?php // use both unset and destroy for compatibility // with all browsers and all versions of PHP session_unset(); session_destroy(); ?>
There are several configurations for PHP sessions which can be set in the
session.use_only_cookies = 1 session.cookie_lifetime = 0 // '0' = expire when browser closes session.cookie_secure = 1 session.cookie_httponly = 1
In PHP 7 or greater, it is also possible to set these values when the session is started.
<?php session_start([ 'use_only_cookies' => 1, 'cookie_lifetime' => 0, 'cookie_secure' => 1, 'cookie_httponly' => 1 ]); ?>