PHP file handling
PHP file handling

PHP file handling: Lesson 7

1. Introduction

Welcome to Lesson 7 of our PHP 8 Free Course! Following Lesson 6, we now delve into the pivotal realm of PHP File Handling. Mastering file handling in PHP is quintessential for creating, reading, writing, and managing files, forming the backbone of numerous web applications. As we traverse this lesson, feel free to review previous content or navigate the course via the PHP 8 Free Course index.

2. Grasping File Paths

Understanding file paths is the stepping stone to proficient PHP file handling.

  • Relative Paths:
  • Relative to the current directory.
  • Example: example.txt or ./dir/example.txt.
  • Absolute Paths:
  • Complete path from the root to the file.
  • Example: /var/www/html/dir/example.txt.

3. Opening and Closing Files

Opening and closing files form the basis of file operations in PHP file handling.

  • Opening Files:
$file = fopen("example.txt", "r");
  • Closing Files:

4. Reading from and Writing to Files

  • Reading Files:
$file = fopen("example.txt", "r");
echo fread($file, filesize("example.txt"));
  • Writing Files:
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");

5. File Uploading and Validation

Uploading files is a common task, yet it requires thorough validation to ensure security and correctness.

File uploading is a common feature in web applications, allowing users to upload images, documents, and other files. However, this feature can be exploited by attackers if not secured properly. Let’s delve into key security measures to ensure safe file uploading in PHP.

  • 1. Restrict File Types:
  • Allow only specific file types to be uploaded to prevent malicious file uploads.
   $allowed_types = array('image/jpeg', 'image/png', 'application/pdf');
   if (!in_array($_FILES['file']['type'], $allowed_types)) {
       echo "Invalid file type!";
  • 2. Validate File Extension:
  • Ensure the file has the correct extension corresponding to its type.
   $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
   if (!in_array($ext, array('jpg', 'png', 'pdf'))) {
       echo "Invalid file extension!";
  • 3. Check File Size:
  • Limit the size of the uploaded files to prevent large file uploads which could exhaust server resources.
   if ($_FILES['file']['size'] > 2000000) {
       echo "File too large!";
  • 4. Generate New File Names:
  • Generate a new, random name for the uploaded file to prevent overwriting existing files and to obfuscate the file path.
   $new_name = uniqid('', true) . '.' . $ext;
  • 5. Set Correct File Permissions:
  • Set restrictive permissions on the uploaded files to prevent unauthorized access.
   move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $new_name);
   chmod('uploads/' . $new_name, 0644);
  • 6. Store Files Outside the Web Root:
  • If possible, store uploaded files outside the web root to prevent direct access via URL.
  • 7. Virus Scanning:
  • Implement server-side virus scanning of uploaded files to detect malicious content.
  • 8. Utilize Content-Disposition Header:
  • When serving files, use the Content-Disposition header to prevent the browser from interpreting files as code.
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
  • 9. Implement CAPTCHA:
  • Employ CAPTCHA mechanisms on the upload form to deter automated malicious uploads.

These security measures are essential for PHP file handling creating a secure file upload feature, thereby safeguarding your PHP application from potential threats and exploits.

  • File Uploading:
    $file = $_FILES['file'];
    move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
  • File Validation:
if ($file['size'] > 500000) {
    echo "File too large";
if ($file['type'] != 'image/jpeg') {
    echo "Only JPEG images allowed";

6. Delving into File Permissions

File permissions dictate what actions can be performed on a file.

  • Checking Permissions:
if (is_readable("example.txt")) {
    echo "The file is readable";
if (is_writable("example.txt")) {
    echo "The file is writable";
  • Setting Permissions:
chmod("example.txt", 0755);

7. Other Useful File Functions

PHP offers a slew of functions for effective file management.

  • File Existence:
if (file_exists("example.txt")) {
    echo "The file exists";
  • File Size:
echo filesize("example.txt");

8. File Locking in PHP

File locking is a mechanism that restricts access to a file by multiple processes, ensuring data integrity.

  • Locking a File:
$file = fopen("example.txt", "w");
if (flock($file, LOCK_EX)) {  // Acquire an exclusive lock
    fwrite($file, "Write something");
    flock($file, LOCK_UN);    // Release the lock
} else {
    echo "Couldn't get the lock!";
  • Shared Locks:
$file = fopen("example.txt", "r");
if (flock($file, LOCK_SH)) {  // Acquire a shared lock
    echo fread($file, filesize("example.txt"));
    flock($file, LOCK_UN);    // Release the lock
} else {
    echo "Couldn't get the lock!";

9. PHP 8 Free Course: Exercises

Now that you’ve garnered a deeper understanding of PHP file handling, it’s time to put that knowledge into practice. Below are exercises designed to reinforce and challenge your file manipulation skills:

  1. Basic File Operations:
    • Create a script to open a file, write some text, read the content, and then close the file. Ensure to handle any potential errors that might occur during these operations.
  2. File Permissions:
    • Write a script to check the permissions of a file and change its permissions. Display the permissions before and after the change.
  3. File Validation:
    • Create a file upload form and write a script to validate the uploaded file. Ensure the file is a PDF and its size is under 2MB.
  4. File Locking:
    • Write a script that demonstrates the use of exclusive and shared locks, ensuring data integrity during file operations.
  5. File Information:
    • Develop a script to display various information about a file, such as its size, last modification time, and type.
  6. Directory Operations:
    • Create a script to make a new directory, list all files within a directory, and then remove the directory.
  7. File Path Manipulation:
    • Write a script to work with relative and absolute file paths, ensuring correct file access regardless of the script’s current directory.

Each exercise aims to provide a hands-on experience, ensuring you’re well-versed in PHP file handling. After completing these exercises, you’ll be better prepared to handle file operations proficiently in your PHP projects.

10. Further Reading and Resources

To delve deeper into file handling and security measures in PHP, here are some resources that provide comprehensive insights:

  1. PHP Manual on Filesystem Functions:
  1. File Upload Security:
  1. File Permissions and Security:
  1. File Locking:
  1. Secure Coding Practices:

These resources are instrumental in understanding the intricacies of file handling and the importance of security measures in PHP. They provide a broader perspective and more detailed information on the topics discussed in this lesson.

Continue your learning journey with Lesson 8: Working with Forms and Data and learn how to securely process user input in PHP. For a broader range of programming topics, visit the programming section on our blog.

Leave a Reply