PHP Cookies Sessions Serialization
PHP Cookies Sessions Serialization
Sure! Here's a detailed but easy-to-understand set of notes on Cookies, Serialization, and
Session State in PHP and MySQL for your Web Technology exam:
1. Cookies
They help websites remember information about the user between different pages or
visits.
php
time() + 3600 sets the cookie expiry time (current time + 3600 seconds).
1/6
Reading a Cookie in PHP
Use the global $_COOKIE array.
php
if(isset($_COOKIE["username"])) {
echo "Welcome " . $_COOKIE["username"];
}
Deleting a Cookie
Set the cookie with a past expiry date:
php
2. Serialization
What is Serialization?
Serialization means converting a PHP variable (like arrays or objects) into a string format
that can be stored or transferred.
Useful when you want to save complex data (arrays, objects) in cookies, sessions, or
databases.
Why Serialize?
Cookies and databases only store strings.
2/6
Serialization converts data structures to strings and unserialization converts it back.
Example
php
$originalData = unserialize($serializedData);
print_r($originalData); // Converts back to the original array
php
When reading:
php
if(isset($_COOKIE["colors"])) {
$colors = unserialize($_COOKIE["colors"]);
print_r($colors);
}
3. Session State
3/6
What is a Session?
A session stores user data on the server to maintain state across multiple page requests.
Sessions allow persistent user-specific data without storing it on the client side.
The server uses this ID to access the stored session data for that user.
php
$_SESSION['username'] = "JohnDoe";
$_SESSION['cart'] = array("apple", "banana");
Destroying a Session
php
session_start();
session_unset(); // Clear all session variables
session_destroy(); // Destroy the session
4/6
Feature Cookies Sessions
You can configure PHP to store session data in MySQL database for persistence and
scalability.
This helps if you have multiple web servers and want centralized session storage.
Summary
Concept Purpose Storage Location Usage Example
Cookies Store small data on client Client (browser) User preferences, login
browser info
If you want, I can also provide simple code examples for each part. Just ask! Good luck for
your exam! 🍀
5/6
Would you like me to prepare notes on related topics like PHP-MySQL connection or
managing state using sessions in detail?
6/6