File Handling in PHP: Reading and Writing Files

Today’s journey takes us through the essential skills of file handling in PHP. In the digital world, files are like the pages of a book, holding valuable information and content. PHP, with its versatile file handling capabilities, allows us to read, write, and manipulate these files with ease. Whether it’s storing user data, managing logs, or handling configuration files, mastering file handling is a skill every PHP developer should have. So, let’s get started!

Understanding File Handling in PHP

File handling in PHP involves reading from and writing to files on the server. It’s like having a librarian who can fetch books (read), write new entries (write), or even update existing records (edit) in a library.

Opening a File

Before you can read from or write to a file, you need to open it using PHP’s fopen() function. This function requires two parameters: the file path and the mode in which to open the file.

File Open Modes:

  • 'r': Open for reading only; start at the beginning of the file.
  • 'w': Open for writing only; start at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • 'a': Open for writing only; start at the end of the file. If the file does not exist, attempt to create it.

Example:

<?php
$file = fopen("example.txt", "r") or die("Unable to open file!");
?>

Reading from a File

Once a file is opened, you can read its content using various PHP functions.

Using fread()

The fread() function reads up to a specified number of bytes from a file.

<?php
echo fread($file, filesize("example.txt"));
fclose($file);
?>

Using fgets()

The fgets() function reads a line from an open file.

<?php
echo fgets($file);
fclose($file);
?>

Writing to a File

Writing to a file is as straightforward as reading from one. You can use fwrite() or file_put_contents().

Using fwrite()

The fwrite() function writes a specified string to a file.

<?php
$file = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Hello, PHP World!\n";
fwrite($file, $txt);
fclose($file);
?>

Using file_put_contents()

This function is a shortcut for a combination of fopen(), fwrite(), and fclose().

<?php
file_put_contents("newfile.txt", "Hello, PHP World!", FILE_APPEND);
?>

Appending to a File

To add content to the end of a file without erasing its existing content, open the file in append mode ('a').

<?php
$file = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Adding more content.\n";
fwrite($file, $txt);
fclose($file);
?>

Checking for File Existence and Size

Before working with a file, it’s often wise to check if it exists and its size.

Using file_exists()

<?php
if(file_exists("example.txt")) {
    echo "File exists.";
} else {
    echo "File does not exist.";
}
?>

Using filesize()

<?php
echo "File size is " . filesize("example.txt") . " bytes";
?>

Deleting a File

Deleting a file in PHP is simple with the unlink() function.

<?php
if (file_exists("deletefile.txt")) {
    unlink("deletefile.txt");
    echo "File deleted.";
} else {
    echo "File does not exist.";
}
?>

Working with CSV Files

PHP can also handle CSV (Comma-Separated Values) files, which are commonly used for spreadsheets and databases.

Reading from a CSV File

<?php
$file = fopen("example.csv", "r");
while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
    print_r($data);
}
fclose($file);
?>

Writing to a CSV File

<?php
$list = array(
    array('Alice', 'Doe', 'alice@example.com'),
    array('Bob', 'Smith', 'bob@example.com')
);

$file = fopen('users.csv', 'w');
foreach ($list as $fields) {
    fputcsv($file, $fields);
}
fclose($file);
?>

Best Practices and Security

When handling files, always follow best practices and keep security in mind:

  • Validate and sanitize all inputs when reading and writing files.
  • Check file types and sizes when dealing with uploads.
  • Ensure error handling is in place to gracefully handle file access issues.
  • Be cautious with file paths to prevent directory traversal attacks.

File handling in PHP is a powerful capability that allows you to store, retrieve, and manipulate data on the server. Whether it’s logging user actions, managing configuration settings, or handling user uploads, understanding how to work with files is a valuable skill in PHP development.

Remember to practice, explore different file handling functions, and think about how you can use these skills to enhance your web projects. The more you work with files, the more comfortable you’ll become. So, enjoy the process and happy coding in the vast world of PHP!