When building web applications, managing files is an essential task. Whether it’s reading data, writing logs, uploading files, or deleting unwanted content, PHP provides robust file-handling functions to get the job done efficiently. In this guide, we’ll cover everything you need to know about PHP file handling with easy-to-follow examples. Let’s dive in!


What is PHP File Handling?

File handling allows you to create, read, write, append, and delete files using PHP. It’s commonly used for:

  • Reading configuration files.

  • Saving form submissions.

  • Logging application activity.

  • Uploading and managing user files.

PHP makes file handling straightforward with built-in functions and superglobals like $_FILES.


Common File System Functions in PHP

Before we explore file operations, here are the most commonly used file-handling functions:

Function Description
fopen() Opens a file.
fclose() Closes a file.
fread() Reads data from a file.
fwrite() Writes data to a file.
file_exists() Checks if a file exists.
unlink() Deletes a file.
fgets() Reads a single line from a file.

How to Open and Read a File in PHP

To read data from a file, you first need to open it using fopen(). Use fread() to retrieve the contents.

Example: Reading a File

$filename = "sample.txt";
if (file_exists($filename)) {
    $file = fopen($filename, "r"); // Open in read mode
    $content = fread($file, filesize($filename));
    fclose($file);
    echo $content;
} else {
    echo "File does not exist.";
}
  • r mode opens the file for reading.

  • Always use file_exists() to check if the file exists to avoid errors.

Reading Line by Line with fgets()

To process a file line by line:

$file = fopen("sample.txt", "r");
while ($line = fgets($file)) {
    echo $line . "<br>";
}
fclose($file);

How to Write to a File in PHP

To write data to a file, use fopen() with write mode (w) or append mode (a).

Example: Writing to a File

$filename = "output.txt";
$file = fopen($filename, "w"); // Open in write mode
fwrite($file, "Hello, World!\n");
fclose($file);
echo "Data written to file.";
  • Write Mode (w): Overwrites existing content or creates a new file.

  • Append Mode (a): Adds content to the end of the file without overwriting.

Appending Data

$file = fopen("output.txt", "a");
fwrite($file, "Appending new content!\n");
fclose($file);
echo "Content appended successfully.";

Deleting a File in PHP

To delete a file, use the unlink() function.

Example: Deleting a File

$filename = "output.txt";
if (file_exists($filename)) {
    unlink($filename);
    echo "File deleted successfully.";
} else {
    echo "File does not exist.";
}
  • Always check if the file exists before attempting to delete it.


Handling File Uploads in PHP

File uploads are essential for user-generated content like images or documents. Use the $_FILES superglobal to manage file uploads.

Example: Uploading a File

Here’s an example of uploading a file using an HTML form:

HTML Form:

<form action="upload.php" method="POST" enctype="multipart/form-data">
    <label for="file">Upload File:</label>
    <input type="file" name="file" id="file">
    <input type="submit" value="Upload">
</form>

PHP Script (upload.php):

if ($_FILES["file"]["error"] == 0) {
    $targetDir = "uploads/";
    $targetFile = $targetDir . basename($_FILES["file"]["name"]);

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
        echo "File uploaded successfully.";
    } else {
        echo "Failed to upload file.";
    }
} else {
    echo "Error during file upload.";
}
  • Ensure the uploads/ directory exists and has proper permissions.

  • Use move_uploaded_file() to move the file to a target directory securely.


File Permissions and Security

Proper file permissions ensure security and prevent unauthorized access:

  • Read Permission: Allows files to be viewed.

  • Write Permission: Allows files to be modified.

  • Use chmod() to set permissions programmatically.

Best Practices:

  1. Validate file types and sizes for uploads.

  2. Avoid exposing sensitive files to public access.

  3. Use file_exists() to prevent overwriting files unintentionally.


Common Mistakes to Avoid

  1. Forgetting to Close Files: Always close files using fclose().

  2. Not Checking File Existence: Use file_exists() to avoid errors.

  3. Ignoring Permissions: Set appropriate permissions using chmod().


Conclusion

With PHP file handling, you can easily manage files—read, write, append, and delete—to enhance your web application’s functionality. By following best practices and handling errors gracefully, you can ensure secure and efficient file management.

For more foundational PHP tutorials, check out these guides:

Keep experimenting with file handling to master PHP!