Lesson 16: Working with Files

In this lesson, you’ll learn how to manage files in PHP. We’ll cover reading and writing files, as well as handling file uploads, which are common tasks in dynamic web applications.


16.1 Reading and Writing Files

Introduction to File Handling

PHP provides several functions to read, write, and manage files:

  1. fopen(): Opens a file for reading, writing, or appending.
  2. fclose(): Closes an open file.
  3. fwrite(): Writes data to a file.
  4. fread(): Reads data from a file.
  5. file_get_contents(): Reads the entire file content as a string.
  6. file_put_contents(): Writes data to a file, overwriting or appending.

Reading Files

Example: Reading File Contents

php
<?php
$file = "example.txt";
// Check if the file exists
if (file_exists($file)) {
$content = file_get_contents($file);
echo “File Content:<br>”;
echo nl2br($content); // Converts newlines to <br> for HTML
} else {
echo “File not found.”;
}
?>

Example: Reading Line by Line

php
<?php
$file = "example.txt";
if (file_exists($file)) {
$handle = fopen($file, “r”); // Open file for reading
while (($line = fgets($handle)) !== false) {
echo $line . “<br>”;
}
fclose($handle); // Close the file
} else {
echo “File not found.”;
}
?>


Writing Files

Example: Writing to a File

php
<?php
$file = "example.txt";
$content = "This is a sample content written to the file.";
if ($handle = fopen($file, “w”)) { // Open file for writing
fwrite($handle, $content);
fclose($handle);
echo “File written successfully.”;
} else {
echo “Unable to write to the file.”;
}
?>

Appending to a File

php
<?php
$file = "example.txt";
$content = "This is an additional line.";
if ($handle = fopen($file, “a”)) { // Open file for appending
fwrite($handle, $content . PHP_EOL); // PHP_EOL adds a newline
fclose($handle);
echo “Content appended successfully.”;
} else {
echo “Unable to append to the file.”;
}
?>


Deleting Files

php
<?php
$file = "example.txt";
if (file_exists($file)) {
unlink($file); // Deletes the file
echo “File deleted successfully.”;
} else {
echo “File does not exist.”;
}
?>


16.2 File Uploads

How File Uploads Work

  1. A file is selected and submitted via an HTML form.
  2. PHP handles the uploaded file using the $_FILES superglobal.
  3. You can validate the file size, type, and name before saving it to the server.

Setting Up a File Upload Form

HTML Form

html
<form action="upload.php" method="POST" enctype="multipart/form-data">
<label for="file">Choose a file:</label>
<input type="file" name="file" id="file" required>
<button type="submit">Upload</button>
</form>

Handling File Uploads in PHP

Basic File Upload Script

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uploadDir = "uploads/"; // Directory where files will be uploaded
$uploadFile = $uploadDir . basename($_FILES["file"]["name"]);
// Move the uploaded file to the desired directory
if (move_uploaded_file($_FILES[“file”][“tmp_name”], $uploadFile)) {
echo “File uploaded successfully: “ . htmlspecialchars(basename($_FILES[“file”][“name”]));
} else {
echo “Error uploading the file.”;
}
}
?>


Validating Uploaded Files

Check File Size

php
if ($_FILES["file"]["size"] > 2000000) { // Limit file size to 2MB
die("Error: File size exceeds 2MB.");
}

Check File Type

php

$allowedTypes = ["image/jpeg", "image/png", "application/pdf"];

if (!in_array($_FILES[“file”][“type”], $allowedTypes)) {
die(“Error: Unsupported file type.”);
}


Improved File Upload Script

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$uploadDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$uploadFile = $uploadDir . $fileName;
// File validation
if ($_FILES[“file”][“size”] > 2000000) {
die(“Error: File size exceeds 2MB.”);
}

$allowedTypes = [“image/jpeg”, “image/png”, “application/pdf”];
if (!in_array($_FILES[“file”][“type”], $allowedTypes)) {
die(“Error: Unsupported file type.”);
}

// Upload the file
if (move_uploaded_file($_FILES[“file”][“tmp_name”], $uploadFile)) {
echo “File uploaded successfully: “ . htmlspecialchars($fileName);
} else {
echo “Error uploading the file.”;
}
}
?>


Display Uploaded Files

php
<?php
$uploadDir = "uploads/";
$files = scandir($uploadDir);
echo “<h3>Uploaded Files:</h3>”;
foreach ($files as $file) {
if ($file !== “.” && $file !== “..”) {
echo “<a href=’$uploadDir$file‘>$file</a><br>”;
}
}
?>


Practical Example

File Management System

  1. Create a folder called uploads in your project directory.
  2. Implement the following features:
    • A form to upload files.
    • A script to list all uploaded files with download links.
    • A delete button next to each file to remove it from the server.

Activities and Exercises

  1. File Reading:
    • Write a script to read and display the content of a .txt file.
    • Count the number of lines in the file.
  2. File Writing:
    • Create a script to log user activity in a log file (activity.log) with timestamps.
  3. File Upload:
    • Create a file upload form that accepts only .jpg and .png files and rejects others.
  4. File Management:
    • Implement a file browser that allows users to upload, view, and delete files.

Assignment

  1. Create a PHP script that:
    • Allows users to upload files.
    • Validates file size (max 5MB) and type (only .pdf and .docx).
    • Stores the uploaded files in a directory named documents.
  2. Extend the script to:
    • Display all uploaded files in a table with options to:
      • Download the file.
      • Delete the file.

Summary

In this lesson, you learned:

  1. How to read and write files in PHP.
  2. How to handle file uploads securely.
  3. How to validate file size and type to ensure safe uploads.

These skills are essential for managing files in dynamic PHP applications. Let me know if you need further clarification or examples!


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *