Unit 4 of 4 · B.Sc IT Sem 4

Unit 4: Cookies, sessions and advanced techniques

Programming in PHP notes · PTU syllabus (BSIT401)

3 min read10 topics10 exam questions
On this page
  1. Unit summary
  2. Setting and deleting cookies
  3. Creating and destroying sessions
  4. Cookies vs sessions
  5. Encoding and decoding session variables
  6. Introduction to FTP and SMTP servers
  7. Math functions
  8. File upload and download
  9. Sending email with PHP
  10. Error tackling and debugging
  11. Requirements analysis for a PHP project
  12. Key terms
  13. Quick revision
  14. 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
ComparisonCookies vs sessions
Cookie
Session

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

1

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.
2

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
?>
3

Topic 3

Cookies vs sessions

HTTP is stateless — each request is independent — so websites use cookies and sessions to remember users.

ComparisonCookies vs sessions
Cookie
Session

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
?>
4

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()
?>
5

Topic 5

Introduction to FTP and SMTP servers

ComparisonFTP and SMTP
FTP
SMTP

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);
?>
6

Topic 6

Math functions

Key termsPHP 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
7

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);
?>
8

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.
9

Topic 9

Error tackling and debugging

Key termsTypes of PHP errors
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.
10

Topic 10

Requirements analysis for a PHP project

ProcessPHP project life cycle
  1. 1

    Requirements

    Users, features, data and reports

  2. 2

    Design

    Pages, database tables (ER diagram) and navigation

  3. 3

    Environment

    XAMPP or LAMP: Apache, PHP, MySQL

  4. 4

    Coding

    Forms, validation, CRUD, sessions, uploads

  5. 5

    Testing

    Valid, invalid and boundary input; security checks

  6. 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

  1. Q1.How do you delete a cookie in PHP?
  2. Q2.Why must setcookie() come before HTML output?
  3. Q3.What does session_destroy() do?
  4. Q4.Distinguish FTP and SMTP.
  5. Q5.Which form attribute is required for file upload?
  6. Q6.Distinguish a warning and a fatal error.

Long-answer questions

  1. Q1.Explain cookies and sessions in PHP with programs.
  2. Q2.Write a PHP program to upload a file with validation and to download a file.
  3. Q3.Explain how email is sent with PHP and the role of SMTP.
  4. 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.

WhatsApp us