Current Location: Home> Latest Articles> Complete Guide to File Read/Write Operations in PHP: Open, Read, Write, and Manage Files

Complete Guide to File Read/Write Operations in PHP: Open, Read, Write, and Manage Files

M66 2025-06-05

Complete Guide to File Handling in PHP: Open, Read, Write, and Manage Files

File handling is a fundamental task in PHP development. Whether you're logging data, storing configuration, or managing user uploads, working with files is essential. This article offers a structured explanation of how to open, read, write, and manage files in PHP, supported by practical code examples.

Opening and Closing Files

The fopen() function is used to open files. Here's a basic syntax example:


$handle = fopen("file.txt", "r");

This code opens the file file.txt in read-only mode and stores the file handle in the $handle variable. PHP supports various file modes, such as:

  • "w": Write mode (truncates the file or creates a new one)
  • "a": Append mode (writes data at the end of the file)
  • "r+": Read/write mode (requires the file to exist)

After completing file operations, always close the file using fclose() to free system resources:


fclose($handle);

Reading from Files

To read data from a file, use the fread() function, which reads a specified number of bytes:


$content = fread($handle, filesize("file.txt"));

This code reads the entire file and stores it in the $content variable. If you prefer reading line by line, use fgets() with a loop:


while (!feof($handle)) {
    $line = fgets($handle);
    echo $line;
}

Writing to Files

Use the fwrite() function to write data to a file. Make sure the file is opened in write or append mode:


$content = "Hello, world!";
fwrite($handle, $content);

Managing Files

1. Renaming Files

The rename() function lets you rename a file:


rename("file.txt", "newfile.txt");

2. Copying Files

Use the copy() function to duplicate a file:


copy("file.txt", "copy.txt");

3. Deleting Files

To remove a file, use unlink():


unlink("file.txt");

4. Checking If a File Exists

You can check whether a file exists using file_exists() and take action accordingly:


if (file_exists("file.txt")) {
    echo "The file exists!";
} else {
    echo "The file does not exist!";
}

Conclusion

This article covered essential PHP file operations, including opening, reading, writing, renaming, copying, deleting, and checking file existence. Mastering these functions allows you to manage file-based data more effectively and write more robust and flexible applications.