Chapter 7: Memory Storage in Browsers
Memory Storage in Browsers
Types of Memory Storage Locations
Two key types to store data in the browser: cookies and sessions.
Both provide quick access to information but are limited in the amount of data they can handle compared to files or databases.
Cookies
General Information about Cookies
Cookies are stored client-side (on the user’s computer).
Primarily used for temporary data storage, with defined expiry dates.
Common uses include pre-filling sign-in forms and storing user preferences.
Key Characteristics
Expiry Dates: Cookies have expiry dates, meaning they are meant for temporary storage.
Common Uses:
Store hashed usernames for automatic sign-ins upon revisiting.
Retain various bits of personal information, including:
Personal information
Location information
Shopping patterns
Advertising preferences
Browsing history
Setting a Cookie
To set a cookie, use the
setcookie()function, which must be placed before the<head>tag or at the top of the HTML document. This ensures that the values are set before they are utilized by HTML or JavaScript.
Code Example for Setting a Cookie
<?php
setcookie(cookie_name, cookie_value, cookie_expiry, cookie_path);
?>
<html>
<body>
<!-- -->
</body>
</html>
Cookie Example Details
cookie_name: Name of the cookie (should be unique and descriptive).
cookie_value: Value assigned to the cookie.
cookie_expiry: Defines when the cookie should expire (delete).
cookie_path: Determines the accessibility of the cookie (use
/for entire domain).
Sample Code to Set a Cookie
setcookie("advertise_pref", "hardware", time() + (86400 * 1), "/");
Retrieving a Cookie Value
Use the superglobal
$_COOKIEvariable to retrieve the cookie value by its name.
Code Example for Retrieving a Cookie
$_COOKIE["advertise_pref"]
Validating a Cookie
Use the
isset()function to check if the cookie exists and is not NULL.
Code Example for Validation
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie " . $cookie_name . " is not set!";
} else {
echo "Cookie " . $cookie_name . " has value: " . $_COOKIE[$cookie_name];
}
Mini Exercise 1: Creating and Printing Cookies
Tasks
Create an HTML page with two forms:
Form 1:
Two text fields:
cookie_nameandcookie_value.Submit button labeled "Add Cookie" to set a new cookie.
Form 2:
Hidden input field
print_cookieswith value true.Submit button labeled "Print Cookies" to read and display all cookies in a table.
Sample Solution Code
<html>
<body>
<form method="POST">
<label for="cookie_name">Cookie Name</label>
<input type="text" name="cookie_name" id="cookie_name"/>
<label for="cookie_value">Value</label>
<input type="text" name="cookie_value" id="cookie_value"/>
<input type="submit" value="Add Cookie"/>
</form>
<form method="POST">
<input type="hidden" name="print_cookies" id="print_cookies" value="true"/>
<input type="submit" value="Print Cookies"/>
</form>
</body>
</html>
Code Execution Section
if (isset($_POST['cookie_name']) && isset($_POST['cookie_value'])) {
setcookie($_POST['cookie_name'], $_POST['cookie_value']);
}
if (isset($_POST['print_cookies'])) {
if ($_POST['print_cookies'] == "true") {
echo "<table><tbody><tr><th>Name</th><th>Value</th></tr>";
foreach ($_COOKIE as $cur_name => $cur_value) {
echo "<tr><td>" . $cur_name . "</td><td>" . $cur_value . "</td></tr>";
}
echo "</tbody></table>";
}
}
Sessions
General Information about Sessions
Sessions store user ID and information server-side, enhancing security compared to cookies.
Unlike cookies, sensitive information such as passwords should never be stored in a session.
Sessions maintain user authentication status by storing a unique user ID for the logged-in user.
Characteristics of Sessions
Session variables persist across multiple web pages and remain valid until the browser is closed.
Authentication with Sessions
Users must authenticate before accessing secured web pages.
Authentication process involves verifying the user's credentials with the server's database.
Upon successful authentication, the user ID is stored in a session.
Starting a Session
To initialize a session, call the
session_start()function before the<html>tag.
Example Session Initialization Code
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Storing User Data in Sessions
After starting a session, use the
$_SESSIONsuperglobal variable to store user data.
Sample Code for User Data Storage
$username_entered = $_POST["username"];
$password_entered = $_POST["password"];
// Validate credentials against database
// If valid, save user ID in session
$_SESSION["username"] = "peter.chong";
Checking Session Variables
Implement authorization checks by verifying if the session variable is set.
Code Example for Authorization Check
if(isset($_SESSION["username"])){
// Display private web page
}
Nullifying the Session Data
To prevent unauthorized access, nullify session variables when a user logs out.
Code for Nullifying Session Data
$_SESSION["username"] = NULL;
Importance of Nullifying Session Data
Nullifying session data prevents subsequent users from accessing the previous user's private information.
Failing to do so can lead to malicious actions, such as changing the user’s password.
Security best practices emphasize eliminating session remnants after user logout.
Chapter 7 Quiz
What sort of data should be stored inside of a session?
a. Password
b. Bank ID
c. Username
d. Advertising preferences
e. Age
When can you call the setcookie() and session_start() functions?
a. Anywhere, as long as it is within a PHP scope
b. Before the tag
c. After the tag
d. Before the tag
e. After the tag
When can you use the $_SESSION superglobal variable?
a. Anytime, like the $_COOKIE superglobal variable
b. Only before the head, at the top of the code
c. Anytime, as long as you have already set a cookie with setcookie()
d. Only after you call the session_start() function
What is the cookie expiry date used for?
a. To delete the cookie once the time has expired so that its value is no longer accessible
b. Once the cookie has expired, the whole web page should be taken down from the server
c. To stop the session superglobal variable from being accessible, the opposite of session_start()
d. Once the cookie has expired, the user should be kicked off the web page and must sign in again
True/False: Passwords should be sent over the server using the POST method and be stored in a session variable.
Chapter 7 Quiz Solutions
Answer: c (Only username appropriate; sensitive information and unrelated preferences should not be stored)
Answer: b (setcookie() and session_start() need to be called before the HTML tag)
Answer: d (Only after sessionstart() is called can $SESSION be used)
Answer: a (Expiry ensures the cookie's value is deleted once expired)
Answer: F (Passwords must never be stored in a cookie or session)
Test Your Knowledge
Create a table comparing the differences between cookies and sessions.
Explain the process of authenticating a user.
Explain why it is important to nullify the username when the user has signed out.
Test Your Knowledge Solutions
Comparative Table:
Cookie
Session
Stored on client browser
Stored on server
Needs
setcookie()for setupNeeds
session_start()to initializeUses superglobal
$_COOKIEUses superglobal
$_SESSIONCan store user preferences
Should be used to store user ID
setcookie()must be called before HTMLsession_start()must be called before HTMLAuthentication Process:
The user inputs their credentials, which are compared to stored credentials on the server.
Anonymous data is processed—if they match, the relevant user ID is stored in a session variable.
Importance of Nullifying:
Prevents unauthorized access to private information after logout, safeguarding against data breaches.