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:
- fopen(): Opens a file for reading, writing, or appending.
- fclose(): Closes an open file.
- fwrite(): Writes data to a file.
- fread(): Reads data from a file.
- file_get_contents(): Reads the entire file content as a string.
- file_put_contents(): Writes data to a file, overwriting or appending.
Reading Files
Example: Reading File Contents
Example: Reading Line by Line
Writing Files
Example: Writing to a File
Appending to a File
Deleting Files
16.2 File Uploads
How File Uploads Work
- A file is selected and submitted via an HTML form.
- PHP handles the uploaded file using the
$_FILES
superglobal. - You can validate the file size, type, and name before saving it to the server.
Setting Up a File Upload Form
HTML Form
Handling File Uploads in PHP
Basic File Upload Script
Validating Uploaded Files
Check File Size
Check File Type
Improved File Upload Script
Display Uploaded Files
Practical Example
File Management System
- Create a folder called
uploads
in your project directory. - 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
- File Reading:
- Write a script to read and display the content of a
.txt
file. - Count the number of lines in the file.
- Write a script to read and display the content of a
- File Writing:
- Create a script to log user activity in a log file (
activity.log
) with timestamps.
- Create a script to log user activity in a log file (
- File Upload:
- Create a file upload form that accepts only
.jpg
and.png
files and rejects others.
- Create a file upload form that accepts only
- File Management:
- Implement a file browser that allows users to upload, view, and delete files.
Assignment
- 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
.
- Extend the script to:
- Display all uploaded files in a table with options to:
- Download the file.
- Delete the file.
- Display all uploaded files in a table with options to:
Summary
In this lesson, you learned:
- How to read and write files in PHP.
- How to handle file uploads securely.
- 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!
Leave a Reply