COOKIES IN PHP:
USING COOKIES IN PHP:
▪Cookie
• An item of data that a web server saves on client’s computer using a web browser.
• Can store 4 KB of data that can be retrieved from client’s computer and returned to the server.
• Can be read only from the web server (domain) that wrote it. • Browsers allow users to turn cookies
off.
• Common uses include session tracking, maintaining data across multiple visits, holding shopping cart
contents, storing login details, and more.
• Is exchanged during the transfer of headers, before the actual HTML of a web page is sent. It is
impossible to send a cookie once any HTML has been transferred
Cookies are created when a website sends a small piece of data to a user's web browser. This data is saved
and sent back to the server whenever the user revisits the website.
Cookies typically contain information like session identifiers, user preferences, or tracking data.
▪Setting a Cookie
• To set up a cookie, call the setcookie function.
• Syntax: setcookie(name, value, expire, path, domain, secure, httponly);
• Example: Create a cookie with the name location and the value USA that is accessible for seven days
across the entire web server on the current domain. setcookie('location', 'USA', time() + 60 * 60 * 24 * 7,
'/'); 5 Table 12-1. The setcookie parameters Parameter Description name The name of the cookie. value
The value of the cookie. Can contain alphanumeric text up to 4 KB. expires The expiry date in UNIX
timestamp format. After this time cookie will become inaccessible. The default value is 0. If not set
cookie expires when the browser closes. path Specify the path on the server for which the cookie will be
available. If set to /, the cookie will be available within the entire domain. domain Specify the domain for
which the cookie is available to e.g., webserver.com or images.webserver.com secure If TRUE, indicates
that the cookie should be sent only if a secure HTTPS connection exists. Default value is FALSE.
Accessing a Cookie
• The value of a cookie can be read by accessing $_COOKIE system array.
• Example: Check whether the current browser has the cookie called location already set and read its
value. if (isset($_COOKIE['location'])) $location = $_COOKIE['location’];
Destroying a Cookie
• To delete a cookie, issue it again with same parameters and only set the value of date in the past.
• Example: Delete the cookie created with the name location and the value USA that is accessible for
seven days. setcookie('location', 'USA', time() - 2592000, '/’);
Types of Cookies
Based on Functionality
1. Session Cookies
o Temporary cookies that are deleted when the browser is closed.
o Used to maintain user sessions (e.g., keeping a user logged in).
2. Persistent Cookies
o Remain on the user's device even after the browser is closed, until they expire or are
manually deleted.
o Used for saving preferences (e.g., language settings) or login information.
3. Secure Cookies
o Sent over HTTPS only, ensuring data security during transmission.
o Used for sensitive information, such as login tokens.
4. HttpOnly Cookies
o Cannot be accessed via JavaScript, reducing the risk of cross-site scripting (XSS) attacks.
5. SameSite Cookies
o Restrict cookies to be sent with cross-site requests, protecting against cross-site request
forgery (CSRF) attacks.
AUTHENTICATION IN PHP:
▪Manage users and passwords for the web application.
▪To use HTTP authentication, PHP sends a header request asking to start an authentication dialog with
the browser.
▪After entering the URL an “Authentication Required” prompt pop up is displayed requiring user name
and password.
Authentication in web technologies refers to the process of verifying the identity of a user, application,
or system before granting access to protected resources. It is a critical component of web security and
ensures that users accessing a web service are who they claim to be.
The values of $_SERVER['PHP_AUTH_USER'] and $_SERVER['PHP_AUTH_PW'] arrays represent the
username and password entered by a user.
▪ These values are then compared with the correct user name and password values. If values are correct,
then user is authenticated.
▪ If user is not authenticated then the following header is issued to define the section as protected and
to display the prompt again: WWW-Authenticate: Basic realm="Restricted Area“
▪ If the user fills out the fields again, the PHP program runs again. But if the user clicks the Cancel
button, the program sends the following header to tell the browser that user is not authorized: HTTP/1.0
401 Unauthorized
HTTP/1.0 401 Unauthorized
Types of Authentication
1.1 Password-Based Authentication
Username and Password: The most common method where users provide a combination of
credentials.
Challenges:
o Vulnerable to brute force, phishing, and credential stuffing attacks.
o Relies on user-generated passwords, which may be weak.
1.2 Multi-Factor Authentication (MFA)
Combines two or more authentication factors:
1. Something you know: Password or PIN.
2. Something you have: OTP (One-Time Password), smartphone, or security token.
3. Something you are: Biometric data like fingerprints or facial recognition.
Enhances security by requiring multiple verification steps.
1.3 Biometric Authentication
Uses unique biological traits for verification:
o Fingerprints, facial recognition, iris scans, voice recognition.
High security but may face issues like hardware limitations and privacy concerns.
1.4 Token-Based Authentication
Uses tokens to authenticate users instead of passwords.
o JSON Web Tokens (JWT): Self-contained tokens encoded with user data.
o Session Tokens: Tokens stored in the server and referenced via cookies.
o OAuth Tokens: Used in OAuth-based systems for third-party access.
Tokens are often short-lived, reducing exposure to session hijacking.
1.5 Certificate-Based Authentication
Relies on digital certificates issued by a trusted Certificate Authority (CA).
Typically used in enterprise applications and HTTPS for secure communication.
1.6 Single Sign-On (SSO)
Users authenticate once and gain access to multiple related systems or applications.
Example: Logging into Google enables access to Gmail, Drive, and other services.
Often implemented with protocols like OAuth 2.0 or SAML (Security Assertion Markup
Language).
1.7 Federated Identity
Extends SSO across different organizations or domains.
Allows users to use their credentials from one platform to access services on another (e.g.,
logging in to a third-party app using a Google or Facebook account).
1.8 Passwordless Authentication
Authentication methods that eliminate the need for passwords:
o Magic Links: One-time links sent via email.
o Biometrics: Fingerprint or face ID.
o Hardware Keys: Devices like YubiKeys.
Example 12-2. PHP authentication with input checking
Storing Usernames and Passwords
▪ Instead of storing password as plain text, convert it into a random string using hash function.
▪password_hash
• Creates a new password hash using a strong one-way hashing algorithm.
• PASSWORD_DEFAULT argument specifies to use the default bcrypt algorithm.
• Example: echo password_hash("mypassword", PASSWORD_DEFAULT); Output returns a string that
includes all the information required for verifying the password:
$2y$10$k0YljbC2dmmCq8WKGf8oteBGiXlM9Zx0ss4PEtb5kz22EoIkXBtbG 13 Storing Usernames and
Passwords
▪password_verify
• Returns TRUE if the correct password for the hash has been supplied and returns FALSE otherwise.
• Example: Match a password given the password’s hash string.
if (password_verify("mypassword", $hash)) echo "Valid"
SESSIONS IN PHP:
▪ Sessions are groups of variables that are stored on the server but relate only to the current user.
▪All session variable values are stored in the global $_SESSION array.
▪ PHP saves a cookie in the user’s web browsers to uniquely identify which variables are applied to
which user. 23 Starting a Session
▪ Start a session by calling the PHP function session_start before any HTML.
▪ Session variables are set using $_SESSION array, like this: $_SESSION['variable'] = $value;
▪A variable can be read back from $_SESSION associative array: $variable = $_SESSION['variable'];
Sessions in web technologies are a mechanism used to maintain state between a user and a web server.
Since HTTP is a stateless protocol, sessions allow web applications to recognize users across multiple
requests and persist data specific to each user.
A session represents a temporary and interactive exchange of information between a user (client) and
a server.
It is created when a user visits a website and persists until the user closes the browser, logs out, or the
session expires.
Each session is typically identified by a unique session ID.
How Sessions Work
1. User Request: The user sends a request to the server (e.g., logs in).
2. Session Creation: The server generates a unique session ID and associates it with session data
stored on the server (e.g., user ID, preferences).
3. Session ID Transmission:
o The session ID is sent to the client and stored in:
Cookies (most common method).
URL parameters (less secure, avoided in modern practices).
Hidden form fields.
4. Subsequent Requests:
o The client includes the session ID in every request (e.g., via cookies).
o The server retrieves the session data using the session ID.
Ending a Session
▪ session_destroy function destroys all of the data associated with the current session. It
does not unset any of the global variables associated with the session, or unset the
session cookie.
▪ Example 12-7. A handy function to destroy a session and its data
Setting a Timeout
▪ Automatically close an inactive user’s session using the ini_set function.
▪ session.gc_maxlifetime specifies the number of seconds after which data will be
cleaned up.
▪ Example: Set the session timeout to exactly one day. ini_set('session.gc_maxlifetime',
60 * 60 * 24);
▪ To determine the current timeout period is, display it using the following: echo
ini_get('session.gc_maxlifetime’);