FahmidasClassroom

Learn by easy steps

Learning Objectives

After completing this tutorial, you will be able to:

  • Create, read, update, and delete text files using PHP.
  • Understand different file handling modes.
  • Upload files from an HTML form to the web server.
  • Validate uploaded files for security.
  • Understand sessions and cookies.
  • Store user information using sessions and cookies.
  • Build a simple login system using sessions.
  • Use AI tools to debug and improve PHP applications.

Introduction

Modern web applications do much more than display information. They save user data, upload images, remember logged-in users, and personalize user experiences. PHP provides built-in features to perform these tasks efficiently.

File handling allows applications to create reports, save logs, store configuration files, and manage text-based information. File upload enables users to upload profile pictures, assignments, documents, and multimedia files.

Sessions and cookies help web applications remember users. For example, when you log in to an online learning platform, your account remains active while you browse different pages. PHP uses sessions and cookies to maintain user information.

In this tutorial, you will learn how to work with files, upload documents securely, and manage user sessions and cookies.

Prerequisites

Before starting this tutorial, you should understand:

  • Variables
  • Functions
  • Forms
  • GET and POST methods
  • PHP superglobals

What is File Handling?

File handling refers to reading from and writing to files stored on the web server.

PHP can:

  • Create files
  • Read files
  • Write data
  • Append data
  • Delete files
  • Copy files
  • Rename files

Opening a File

The fopen() function opens a file.

Syntax

$file = fopen(“students.txt”, “r”);

The second parameter specifies the file mode.

Common file modes

Mode Description
r Read only
w Write only and overwrite existing data
a Append data to the end of a file
x Create a new file
r+ Read and write
w+ Read and write after deleting previous contents

Creating a File

The following code will create the file named students.txt.

<?php

$file = fopen("students.txt", "w");
fclose($file);
echo "File Created Successfully.";

?>

Output:

Writing to a File

The following code will write a line in the students.txt file.

<?php

$file = fopen("students.txt","w");
fwrite($file,"Learning PHP File Handling");
fclose($file);

?>

Output:

Appending Data

The following code will append a line in the students.txt file.

<?php

$file = fopen("students.txt","a");
fwrite($file,"\nWelcome to Web Programming.");
fclose($file);

?>

Output:

Reading a File

<?php

$file = fopen("students.txt","r");
echo fread($file, filesize("students.txt"));
fclose($file);

?>

Output:

Reading File Line by Line

<?php

$file = fopen("students.txt","r");
while(!feof($file))
{
     echo fgets($file)."<br>";
}
fclose($file);

?>

Output:

Checking Whether a File Exists

<?php

if(file_exists("students.txt"))
{
    echo "File Found.";
}
else
{
     echo "File Not Found.";
}

?>

Output:

Deleting a File

<?php

unlink("students.txt");
echo "File Deleted.<br/>";
if(file_exists("students.txt"))
{
    echo "File Found.";
}
else
{
    echo "File Not Found.";
}

?>

Output:

What is File Upload?

File upload allows users to send files from their computers to the web server.

Common uploaded files include:

  • Images
  • PDF documents
  • Assignments
  • Videos
  • Audio files

Creating a File Upload Form

The form must use the POST method and enctype=”multipart/form-data“.

<!DOCTYPE html>

<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
     Select File:
     <input type="file" name="myFile">
     <br><br>
     <input type="submit" value="Upload">
</form>
</body>
</html>

Understanding the $_FILES Superglobal

PHP stores uploaded file information inside the $_FILES array.

Common properties include:

$_FILES[“myFile”][“name”]

Original file name

$_FILES[“myFile”][“tmp_name”]

Temporary file location

$_FILES[“myFile”][“size”]

File size

$_FILES[“myFile”][“type”]

File type

$_FILES[“myFile”][“error”]

Upload status

Uploading a File

<?php

$target = "uploads/" . basename($_FILES["myFile"]["name"]);
if(move_uploaded_file($_FILES["myFile"]["tmp_name"],$target))
{
      echo "File Uploaded Successfully.";
}
else
{
      echo "Upload Failed.";
}

?>

Create an uploads folder inside your project before running the program.

Output:

The following output will appear running the file_upload.html file.

After selecting the dummy.txt file that exists in the current location, the following output will appear.

Validating Uploaded Files

Always validate uploaded files before saving them.

Check file size:

<?php

if($_FILES["myFile"]["size"] > 2000000)
{
     echo "File is too large.";
}

?>

Allow only image files:

<?php

$type = pathinfo($_FILES["myFile"]["name"],PATHINFO_EXTENSION);
if($type=="jpg" || $type=="png" || $type=="jpeg")
{
     echo "Valid Image";
}
else
{
     echo "Invalid File Type";
}

?>

What is a Session?

  • HTTP is a stateless protocol. Each request is treated independently.
  • A session allows PHP to store user information across multiple pages.
  • Sessions are stored on the server.

Starting a Session

Every PHP page that uses sessions must begin with session_start().

<?php

session_start();
$_SESSION["username"]="nirob";
echo "Session Created.";

?>

Accessing Session Data

<?php

session_start();
echo $_SESSION["username"];

?>

Removing Session Data

<?php

session_start();
session_unset();
session_destroy();
echo "Session Removed.";

?>

Example Login Using Sessions

login.php

<?php

session_start();
$_SESSION["user"]="admin";
header("Location: https://localhost/php_lab/dashboard.php");

?>

dashboard.php

<?php

session_start();
if(isset($_SESSION["user"]))
{
     echo "Welcome ".$_SESSION["user"];
}
else
{
     echo "Please Login.";
}

?>

Output:

The following output will appear after executing the login.php page.

What is a Cookie?

A cookie stores small pieces of information inside the user’s browser.

Unlike sessions, cookies remain available even after the browser is closed if an expiration time is specified.

Creating a Cookie

<?php

setcookie("username","Nirob",time()+3600);
echo "Cookie Created.";

?>

The cookie expires after one hour.

Reading a Cookie

<?php 
echo $_COOKIE["username"]; 
?>

Deleting a Cookie

<?php

setcookie("username","",time()-3600);
echo "Cookie Deleted.";

?>

Session vs Cookie

Session Cookie
Stored on the server Stored in the browser
More secure Less secure
Ends when session expires Can remain after browser closes
Suitable for authentication Suitable for user preferences

Example 1

Save Student Information in a File

<?php

$file = fopen("students.txt","a");
fwrite($file,"Rahim, CSE, 3.85\n");
fclose($file);
echo "Record Saved.";

?>

 

Example 2

Display Student Records

<?php

    echo file_get_contents("students.txt");

?>

 

Example 3

Remember User Name with a Cookie

<?php

setcookie("student","Rahim",time()+86400);
echo "Welcome Back.";

?>

 

Example 4

Count Page Visits

<?php

session_start();
if(!isset($_SESSION["count"]))
{
    $_SESSION["count"]=1;
}
else
{
    $_SESSION["count"]++;
}
echo "Visited ".$_SESSION["count"]." times.";

?>

Example 5

Display Uploaded File Name

<?php

   echo $_FILES["myFile"]["name"];

?>

 

Lab Tasks:

Task 1

Create a text file and write your personal information.

Task 2

Append additional information to the file.

Task 3

Read and display the file contents.

Task 4

Create an HTML form for uploading images.

Task 5

Validate uploaded images by file extension.

Task 6

Create a session that stores a student’s name.

Task 7

Display the session value on another page.

Task 8

Create a cookie that remembers the user’s preferred language.

Exercises:

  1. Develop a simple note management system that stores notes in text files.
  2. Create a file upload system that accepts only PDF documents.
  3. Build a photo gallery that automatically displays uploaded images.
  4. Create a visitor counter using sessions.
  5. Develop a login system that combines sessions and cookies.
  6. Create a profile page that remembers the user’s preferred theme using cookies.
  7. Build a student assignment submission system with secure file upload validation.

Summary

In this tutorial, you learned how to create, read, update, and delete files using PHP. You explored secure file upload techniques using HTML forms and the $_FILES superglobal. You also learned how sessions maintain user information across multiple pages and how cookies store data in the user’s browser. These concepts are essential for building interactive, secure, and user-friendly