Mastering PHP: From Basics to Building Dynamic Web Applications

0 0 0 0 0

Chapter 6 : Sessions, Cookies & File Handling


🔹 1. Introduction

As users interact with your application, you need ways to:

  • Remember who they are
  • Store temporary or persistent data
  • Read, write, or upload files

PHP provides built-in support for sessions, cookies, and file management — critical for login systems, personalization, and content-driven apps.


🔹 2. PHP Sessions – Storing Data Across Pages

Sessions store data on the server and assign a unique ID to each user. It's ideal for storing:

  • Login status
  • User preferences
  • Temporary values between pages

Starting a Session:

session_start(); // Must be at the top of the file

 

$_SESSION["username"] = "john";

echo $_SESSION["username"]; // Output: john

Unsetting and Destroying:

unset($_SESSION["username"]); // remove one

session_destroy(); // clear all session data

Function

Purpose

session_start()

Initiates session

$_SESSION[]

Access or assign session values

session_destroy()

Ends session

️ Always call session_start() before any HTML output.


🔹 3. PHP Cookies – Storing Data on the Client Side

Cookies are stored in the user's browser and are useful for:

  • Remembering login (if permitted)
  • Saving theme preferences
  • Tracking visits

Setting a Cookie:

setcookie("user", "john", time() + (86400 * 7)); // 7 days

Reading a Cookie:

echo $_COOKIE["user"];

Deleting a Cookie:

setcookie("user", "", time() - 3600); // Expired

Function

Purpose

setcookie()

Creates a cookie

$_COOKIE[]

Access a cookie value


🔹 4. File Uploads in PHP

To accept file uploads, your form must use enctype="multipart/form-data".

Upload Form:

<form method="post" enctype="multipart/form-data">

  <input type="file" name="upload">

  <input type="submit" name="submit">

</form>

Upload Handling:

if (isset($_FILES["upload"])) {

  $file = $_FILES["upload"];

  $name = $file["name"];

  $tmp = $file["tmp_name"];

 

  move_uploaded_file($tmp, "uploads/" . $name);

  echo "Uploaded!";

}

Use is_uploaded_file() and validate the file size/type for security.


🔹 5. Reading and Writing Files in PHP

Writing to a File:

$file = fopen("data.txt", "w");

fwrite($file, "Hello World!");

fclose($file);

Reading a File:

$file = fopen("data.txt", "r");

$content = fread($file, filesize("data.txt"));

fclose($file);

echo $content;

Mode

Meaning

r

Read only

w

Write (overwrite)

a

Append


🔹 6. File Existence & Deletion

Check If File Exists:

if (file_exists("data.txt")) {

  echo "File exists.";

}

Delete File:

unlink("data.txt");


🔹 7. Real-World Example: Visit Counter with File

$file = "counter.txt";

 

if (file_exists($file)) {

  $count = (int)file_get_contents($file);

} else {

  $count = 0;

}

 

$count++;

file_put_contents($file, $count);

echo "You are visitor #$count";

file_get_contents() and file_put_contents() are simpler alternatives to fopen().


🔹 8. Session vs Cookie: When to Use What?

Feature

Session

Cookie

Stored

On server

On client browser

Secure

More secure

Less secure (client-side)

Size

Unlimited

~4KB max

Lifetime

Until browser closed or session_destroy()

Defined manually


🔹 9. Summary Table


Task

Method

Start session

session_start()

Set session variable

$_SESSION["key"] = "value"

Set cookie

setcookie("key", "value", expiry)

Upload file

move_uploaded_file()

Read file

fread(), file_get_contents()

Delete file

unlink("file.txt")

Back

FAQs


1. What is PHP used for?

PHP is primarily used for creating dynamic web pages and server-side applications such as login systems, e-commerce platforms, and CMSs.

2. Is PHP still relevant in 2025?

Absolutely. PHP continues to power most of the web and is essential in WordPress, Laravel, and web hosting environments.

3. Do I need to install anything to run PHP?

Yes — you can install XAMPP, MAMP, Laragon, or PHP CLI for local development.

4. What databases work with PHP?

MySQL is the most commonly used with PHP, but it also supports PostgreSQL, SQLite, and others.

5. What’s the difference between PHP and JavaScript?

PHP is a server-side scripting language, while JavaScript is primarily client-side, running in the browser.

6. Can I use PHP with HTML?

Yes PHP is often embedded inside HTML to create dynamic pages

7. What is a PHP file extension?

PHP files have the .php extension and are executed on the server.

8. How do I send data from a form to PHP?

Use method="POST" or method="GET" in your form and access data in PHP using $_POST or $_GET.

9. Is PHP good for building APIs?

Yes — PHP can be used to build RESTful APIs, especially with frameworks like Laravel or Slim.

10. What are some popular PHP frameworks?

Laravel, Symfony, CodeIgniter, Zend, and Slim are among the most used PHP frameworks.