Unit 4: Cookies, sessions and advanced techniques
Programming in PHP notes · PTU syllabus (BSIT401)
On this page
- Unit summary
- Setting and deleting cookies
- Creating and destroying sessions
- Cookies vs sessions
- Encoding and decoding session variables
- Introduction to FTP and SMTP servers
- Math functions
- File upload and download
- Sending email with PHP
- Error tackling and debugging
- Requirements analysis for a PHP project
- Key terms
- Quick revision
- Important questions
Unit summary
Real web applications remember users, send email, accept uploads and must be debugged. This unit covers cookies and sessions, encoding and decoding session variables, FTP and SMTP, math functions, file upload and download, email, error handling and debugging, and requirements analysis for a PHP project.
After this unit you can
- Set and delete cookies; create and destroy sessions
- Encode and decode session data
- Upload and download files and send email
- Handle errors and plan a PHP project
PTU syllabus topics
- Setting and deleting cookies
- session creation and destruction
- encoding/decoding session variables
- FTP/SMTP server introduction
- math functions
- file upload/download
- email with PHP
- error tackling and debugging
- PHP project requirements analysis
Stored on
The browser
The server
Security
Less: user can see and edit
More secure
Size
Small (about 4 KB)
Larger
Lifetime
Until its expiry date
Until the browser closes or timeout
Topic 1
Setting and deleting cookies
php<?php
// set: name, value, expiry (30 days), path
setcookie("theme", "dark", time() + 30 * 24 * 60 * 60, "/");
// read (available from the next request)
echo $_COOKIE["theme"] ?? "light";
// delete: set expiry in the past
setcookie("theme", "", time() - 3600, "/");
?>- setcookie() must be called before any HTML output, because cookies travel in HTTP headers.
Topic 2
Creating and destroying sessions
php<?php
// login.php
session_start();
if ($user_ok) {
session_regenerate_id(true); // prevent session fixation
$_SESSION["user"] = $username;
$_SESSION["role"] = "student";
header("Location: dashboard.php");
}
// dashboard.php
session_start();
if (!isset($_SESSION["user"])) { header("Location: login.php"); exit; }
echo "Welcome " . $_SESSION["user"];
// logout.php
session_start();
$_SESSION = []; // clear variables
session_destroy(); // end the session
?>Topic 3
Cookies vs sessions
HTTP is stateless — each request is independent — so websites use cookies and sessions to remember users.
Stored on
The user's browser
The server
Security
Less secure (user can see and edit)
More secure
Size
Small (about 4 KB)
Larger
Lifetime
Until its expiry time
Until logout or timeout
PHP
setcookie(), $_COOKIE
session_start(), $_SESSION
php<?php
session_start();
$_SESSION["user"] = "ana"; // store
echo $_SESSION["user"]; // read on any page after session_start()
session_destroy(); // logout
?>Topic 4
Encoding and decoding session variables
- PHP stores session data as a serialised string; session_encode() returns that string for the current session and session_decode() restores variables from such a string.
php<?php
session_start();
$_SESSION["user"] = "aman";
$_SESSION["cart"] = 3;
$data = session_encode(); // user|s:4:"aman";cart|i:3;
session_decode($data); // repopulates $_SESSION
// general-purpose alternatives: serialize()/unserialize(), json_encode()/json_decode()
?>Topic 5
Introduction to FTP and SMTP servers
Full form
File Transfer Protocol
Simple Mail Transfer Protocol
Purpose
Uploading and downloading files to a server
Sending email between mail servers
Ports
21 (control), 20 (data); SFTP over SSH uses 22
25; 587 for submission with TLS
In PHP
ftp_connect, ftp_login, ftp_put, ftp_get
mail() or libraries such as PHPMailer
php<?php
$ftp = ftp_connect("ftp.example.com");
ftp_login($ftp, "user", "password");
ftp_put($ftp, "public_html/index.php", "index.php", FTP_BINARY);
ftp_close($ftp);
?>Topic 6
Math functions
- abs, ceil, floor, round
- Absolute value and rounding
- sqrt, pow, exp, log
- Roots, powers and logarithms
- max, min, array_sum
- Largest, smallest, total
- rand, mt_rand, random_int
- Random numbers (random_int is cryptographically secure)
- pi, sin, cos, tan, deg2rad
- Trigonometry
- intdiv, fmod
- Integer division and float remainder
- number_format, base_convert, bindec, decbin
- Formatting and base conversion
Topic 7
File upload and download
php<!-- form -->
<form method="post" enctype="multipart/form-data">
<input type="file" name="photo"> <button>Upload</button>
</form>
<?php
if (isset($_FILES["photo"]) && $_FILES["photo"]["error"] === 0) {
$allowed = ["jpg", "jpeg", "png"];
$ext = strtolower(pathinfo($_FILES["photo"]["name"], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) echo "Only JPG or PNG allowed";
elseif ($_FILES["photo"]["size"] > 2e6) echo "Maximum 2 MB";
else {
$target = "uploads/" . uniqid() . "." . $ext;
move_uploaded_file($_FILES["photo"]["tmp_name"], $target);
echo "Uploaded";
}
}
// download.php — force the browser to download a file
$file = "uploads/syllabus.pdf";
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");
header("Content-Length: " . filesize($file));
readfile($file);
?>Topic 8
Sending email with PHP
php<?php
$to = "student@example.com";
$subject = "Admission confirmed";
$message = "Dear student, your admission to B.Sc IT is confirmed.";
$headers = "From: admissions@example.com\r\nContent-Type: text/plain; charset=UTF-8";
if (mail($to, $subject, $message, $headers)) echo "Mail sent";
else echo "Mail failed";
?>- mail() needs an SMTP server configured in php.ini; for authenticated SMTP, HTML mail and attachments, use PHPMailer or a mail API.
Topic 9
Error tackling and debugging
- Parse (syntax) error
- Missing semicolon or bracket; script does not run
- Fatal error
- Calling an undefined function; script stops
- Warning
- Including a missing file; script continues
- Notice
- Using an undefined variable; minor
- Exception
- Error object thrown and caught with try–catch
php<?php
error_reporting(E_ALL); // report everything during development
ini_set("display_errors", 1); // turn OFF on a live server; log instead
function divide($a, $b) {
if ($b == 0) throw new Exception("Division by zero");
return $a / $b;
}
try {
echo divide(10, 0);
} catch (Exception $e) {
error_log($e->getMessage()); // write to the log file
echo "Something went wrong";
} finally {
echo " — done";
}
?>- Debugging aids: echo, var_dump(), print_r(), die(), error logs and Xdebug breakpoints.
Topic 10
Requirements analysis for a PHP project
- 1
Requirements
Users, features, data and reports
- 2
Design
Pages, database tables (ER diagram) and navigation
- 3
Environment
XAMPP or LAMP: Apache, PHP, MySQL
- 4
Coding
Forms, validation, CRUD, sessions, uploads
- 5
Testing
Valid, invalid and boundary input; security checks
- 6
Deployment
Hosting, domain, backups
Example
Student attendance system: requirements — teachers log in, mark attendance per class, students view their percentage, admin prints reports. Tables: users, students, classes, attendance(date, roll, status).
Key terms
- Cookie
- Small piece of data stored in the browser
- Session
- Server-side storage of user data across pages
- session_encode
- Function returning session data as a string
- SMTP
- Protocol for sending email
- Exception
- Error object thrown and caught with try–catch
Quick revision
- setcookie(name, value, expiry); delete by past expiry.
- session_start, $_SESSION, session_regenerate_id, session_destroy.
- session_encode, session_decode; serialize, json_encode.
- FTP (files, port 21), SMTP (mail, ports 25 and 587); ftp_put, mail().
- Math functions; uploads with $_FILES and move_uploaded_file; download headers; error types; try–catch; project requirements.
Important exam questions
Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).
Short-answer questions
- Q1.How do you delete a cookie in PHP?
- Q2.Why must setcookie() come before HTML output?
- Q3.What does session_destroy() do?
- Q4.Distinguish FTP and SMTP.
- Q5.Which form attribute is required for file upload?
- Q6.Distinguish a warning and a fatal error.
Long-answer questions
- Q1.Explain cookies and sessions in PHP with programs.
- Q2.Write a PHP program to upload a file with validation and to download a file.
- Q3.Explain how email is sent with PHP and the role of SMTP.
- Q4.Explain error handling and debugging techniques in PHP.
Stuck on this unit?
Message SBS on WhatsApp for help with Programming in PHP, or to ask about studying B.Sc IT at Synetic.
