Internet Programming II - 2017EC
Chapter 5
MANAGING STATE, TIME, PASSWORD, and CODE REUSABILITY
5.1. Sessions and Cookies
State Management
HTTP is a stateless protocol, meaning each request from a client to a server is independent. The server
does not retain any memory of previous requests. However, web applications often need to remember
user-specific data, such as login status, shopping cart items, and preferences. To achieve this, we use state
management techniques like Sessions and Cookies.
Sessions
A session allows data to be stored on the server and linked to a unique session ID, which is stored on the
client-side in a cookie. This makes sessions more secure compared to cookies since sensitive information
is not stored directly on the client’s device.
To start a session in PHP, use the session_start() function at the beginning of your script:
session_start();
Once a session is started, data can be stored in the $_SESSION superglobal array:
session_start();
$_SESSION['username'] = 'JohnDoe';
$_SESSION['role'] = 'admin';
To access session data, simply use:
session_start();
echo "Welcome, " . $_SESSION['username'];
If you need to remove a specific session variable, use unset(), and to completely destroy a session, use
session_destroy():
unset($_SESSION['username']); // Remove only the username variable
session_destroy(); // Destroy all session data
1 of 8
Internet Programming II - 2017EC
Cookies
A cookie is a small file stored on the user’s device by the web browser. It is mainly used to remember user
preferences, login credentials, and browsing history across sessions.
To set a cookie in PHP, use the setcookie() function:
setcookie("username", "JohnDoe", time() + (86400 * 30), "/");
This creates a cookie named username with the value JohnDoe, which expires in 30 days. The /
parameter ensures that the cookie is available across the entire website.
To read a cookie, access the $_COOKIE superglobal:
if(isset($_COOKIE['username'])) {
echo "Hello, " . $_COOKIE['username'];
} else {
echo "Welcome, guest!";
}
To delete a cookie, set its expiration time to a past date:
setcookie("username", "", time() - 3600, "/");
Examples
1. “Remember Me” functionality, if a user selects the “Remember Me” option on a login form, a
cookie can store an authentication token so that the user remains logged in:
if(isset($_POST['remember_me'])) {
setcookie("auth_token", md5($_POST['username'] . time()), time() + (86400
* 30), "/");
2. Cookies are also used to store user preferences, such as dark mode settings or language selection.
For instance, a site could store a theme preference:
setcookie("theme", "dark", time() + (86400 * 30), "/");
And retrieve it later:
if(isset($_COOKIE['theme']) && $_COOKIE['theme'] == 'dark') {
echo "<link rel='stylesheet' href='dark-theme.css'>";
2 of 8
Internet Programming II - 2017EC
5.2. PHP Date and Time
PHP provides several powerful functions to handle date and time.
Get Current Date/Time
The date() function is commonly used to fetch the current date and time. It takes two parameters: the
format and an optional timestamp.
Task Code Example Output Example
current date echo date("Y-m-d"); 2025-03-20
current time echo date("H:i:s"); 14:35:23
full date/time echo date("Y-m-d H:i:s"); 2025-03-20 14:35:23
Format Date and Time
The date() function supports a wide range of formatting characters to customize output.
Get a Time
Here are some characters commonly used for times:
Character Description Example Output
H 24-hour format of an hour (00 to 23) 14
h 12-hour format of an hour with leading zeros (01 to 12) 02
i Minutes with leading zeros (00 to 59) 35
s Seconds with leading zeros (00 to 59) 23
a Lowercase Ante meridiem and Post meridiem (am or pm) pm
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Character Description Example Output
d Represents the day of the month (01 to 31) 20
m Represents a month (01 to 12) 03
Y Represents a year (in four digits) 2025
l (lowercase 'L') Represents the day of the week Thursday
Other characters, like /, ., or - can also be inserted between the characters to add additional formatting.
Example:
// Format today's date in different ways
echo date("d/m/Y"); // Output: 20/03/2025
echo date("m-d-Y"); // Output: 03-20-2025
echo date("l, F j, Y"); // Output: Thursday, March 20, 2025
3 of 8
Internet Programming II - 2017EC
Get Timestamps
A timestamp is the number of seconds since January 1, 1970 (Unix Epoch). PHP uses this internally for
date manipulation.
// Get current timestamp
echo time(); // Output: 1710942923
Convert Timestamp to Date
You can convert a timestamp back to a readable date:
$timestamp = time();
echo date("Y-m-d H:i:s", $timestamp); // Output: 2025-03-20 14:35:23
Date Manipulation
Add/Subtract Dates
You can use strtotime() to add or subtract time from a date.
Operation Code Output
Add 7 days echo date("Y-m-d", strtotime("+7 days")); 2025-03-27
Subtract 1 month echo date("Y-m-d", strtotime("-1 month")); 2025-02-20
Add 1 year, 2 echo date("Y-m-d", strtotime("+1 year 2 months 3 2026-05-23
months, 3 days days"));
Calculate Date Difference
To calculate the difference between two dates, use DateTime objects.
$date1 = new DateTime("2025-03-20");
$date2 = new DateTime("2025-04-05");
$interval = $date1->diff($date2);
echo $interval->days; // Output: 16
You can also access differences in other formats:
echo $interval->y . ' years, '; // Output: 0 years
echo $interval->m . ' months, '; // Output: 0 months
echo $interval->d . ' days'; // Output: 16 days
Timezones
Handling different timezones is essential for global applications.
Set and Get Timezone
// Set timezone
date_default_timezone_set("America/New_York");
4 of 8
Internet Programming II - 2017EC
// Display date in the new timezone
echo date("Y-m-d H:i:s"); // Output: 2025-03-20 09:35:23
// Get current timezone
echo date_default_timezone_get(); // Output: America/New_York
Convert Between Timezones
$date = new DateTime("now", new DateTimeZone("UTC"));
$date->setTimezone(new DateTimeZone("Asia/Tokyo"));
echo $date->format("Y-m-d H:i:s"); // Output: 2025-03-21 01:35:23
5.3. Include and Require
In PHP, include and require are essential for efficient code reuse, helping maintain clean, organized scripts
by allowing you to write code once and include it wherever needed — promoting reusability, simplifying
maintenance (e.g., updating a shared navigation bar in one place reflects across all instances), and
supporting modularity by breaking large scripts into smaller, manageable parts.
Example:
// contents of header.php
echo "<h1>Welcome to My Website</h1>";
// main script
include 'header.php';
echo "<p>Homepage content goes here.</p>";
Output:
Welcome to My Website
Homepage content goes here.
Include vs Require
Both include and require bring in content from another file, but they behave differently when the file
is missing or has an error.
Function Behavior if file is missing Typical Use Case
include Issues a warning and continues script execution Non-critical parts (e.g., ads)
require Throws a fatal error and stops script execution Essential parts (e.g., config files)
5 of 8
Internet Programming II - 2017EC
Example with include:
include 'nonexistent.php';
// Warning displayed, but script continues
echo "This still runs!";
Example with require:
require 'nonexistent.php';
// Fatal error: script stops
echo "This will NOT run!";
include_once() / require_once()
Sometimes, you only want a file to load once — especially for configuration files or classes.
Function Description
include_once() Includes the file only if it hasn’t been included already.
require_once() Requires the file only if it hasn’t been required already.
Example:
include_once 'config.php';
include_once 'config.php'; // This won’t load again
require_once 'functions.php';
require_once 'functions.php'; // Also won’t reload
5.4. Password Hashing and Security
Storing passwords in plain text is extremely risky — if an attacker gains access to the database, they can
immediately misuse user accounts. Hashing transforms the password into a fixed-length string, making it
difficult to reverse-engineer, ensuring that even if data is leaked, the original password remains protected.
Hashing Methods Overview
MD5 and SHA1:
MD5 produces a 128-bit hash, and SHA1 generates a 160-bit hash. Both are fast and widely supported,
making them popular in the early days of web development. However, Both algorithms suffer from
collision attacks (where two different inputs produce the same hash). Their speed, once an advantage,
now allows attackers to brute-force passwords quickly using modern hardware.
6 of 8
Internet Programming II - 2017EC
Example of MD5 (not recommended):
$password = "mypassword";
$hash = md5($password);
echo $hash; // Outputs a hashed string, but it's insecure!
Modern Secure Hashing
password_hash() PHP provides the password_hash() function, designed to handle secure password
hashing easily. It automatically generates a salt (a random string added to the password before hashing),
strengthening the result and preventing rainbow table attacks.
Example:
$password = "my_secure_password";
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
echo $hashedPassword; // Outputs a secure, salted hash
PASSWORD_DEFAULT uses the strongest algorithm available (currently bcrypt).
You can also specify PASSWORD_BCRYPT or PASSWORD_ARGON2I/ID for more control.
Verifying Passwords
password_verify() checks if a provided password matches the stored hash:
if (password_verify($password, $hashedPassword)) {
echo "Password is correct!";
} else {
echo "Invalid password.";
}
This function ensures hashes are compared securely without timing attacks.
Example with login simulation:
$storedHash = password_hash("securepass123", PASSWORD_DEFAULT);
$userInput = "securepass123";
if (password_verify($userInput, $storedHash)) {
echo "Login successful!";
} else {
echo "Incorrect password.";
}
7 of 8
Internet Programming II - 2017EC
Salting
A salt is a unique random string added to the password before hashing, ensuring identical passwords yield
different hashes. PHP’s password_hash() handles salting automatically, making manual salt creation
unnecessary.
Example of manual salting (before PHP 5.5):
$salt = bin2hex(random_bytes(22));
$hashedPassword = hash('sha256', $salt . $password);
Hashing Algorithms
bcrypt: Uses the Blowfish cipher, generating a 60-character hash. It includes built-in salting and adjustable
cost (work factor), slowing down brute-force attempts.
$hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' =>
12]);
Example:
$password = "mypassword";
$bcryptHash = password_hash($password, PASSWORD_BCRYPT, ['cost' =>
10]);
echo $bcryptHash;
argon2: A newer, memory-hard algorithm designed to resist both brute-force and GPU-based attacks. PHP
supports PASSWORD_ARGON2I and PASSWORD_ARGON2ID.
$hashedPassword = password_hash($password, PASSWORD_ARGON2ID);
Example:
$argonHash = password_hash($password, PASSWORD_ARGON2ID,
['memory_cost' => 1<<12, 'time_cost' => 4, 'threads' => 2]);
echo $argonHash;
8 of 8