Skip to Content
Course content

34: File Handling in PHP

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Think of file handling in PHP like using a physical filing cabinet in an office. You don't just magically know what's inside a folder; first, you have to walk over to the cabinet and open a specific drawer. Once it's open, you have a "handle" on that drawer. You can either read the documents inside, scribble some new notes on a page, or add a completely new sheet to the back. But the most important part? When you're done, you have to close the drawer. If you leave it open, you're wasting space, and in a busy office, someone's going to walk right into it.

In PHP, that "handle" is a resource variable. You use fopen() to open the drawer, and the "mode" you choose tells PHP whether you're there to just look (read), replace everything (write), or add to the end (append).

Grabbing a Handle on Your Data

To do anything with a file, you first need to establish a connection to it. I usually see people trip up on the "modes" here. If you use 'w', PHP will truncate the file—meaning it wipes everything out the moment you open it. If you just want to add to a log, you'll want 'a' for append.

// Let's create a simple activity log
$fileHandle = fopen("activity_log.txt", "a"); 

if ($fileHandle) {
    echo "Drawer opened successfully!";
} else {
    echo "Couldn't open the file. Check your permissions.";
}

Adding New Entries Without Deleting the Old Ones

Once you have that handle, you use fwrite(). I always recommend adding a newline character (\n) at the end of your strings. If you don't, PHP will just smash all your entries together on one giant, unreadable line. I've spent way too many hours debugging logs that looked like one long sentence because I forgot a simple \n.

$timestamp = date("Y-m-d H:i:s");
$message = "User 42 logged in at $timestamp\n";

fwrite($fileHandle, $message);

Pulling Data Back Out

Reading is where things get interesting. You can read the whole file at once, but if that file grows to be 100MB, your server's memory will scream. Instead, it's better to read the file line by line using a while loop and fgets(). This keeps your memory footprint tiny because you're only holding one line at a time.

$readHandle = fopen("activity_log.txt", "r");

if ($readHandle) {
    while (($line = fgets($readHandle)) !== false) {
        echo "Log Entry: " . htmlspecialchars($line) . "
"; } }

Don't Forget to Tidy Up

Remember the filing cabinet analogy? Closing the drawer is non-negotiable. Use fclose(). While PHP usually closes files automatically when the script ends, relying on that is a bad habit. In a larger application, leaving file handles open can lead to "too many open files" errors, which will crash your process.

fclose($fileHandle);
fclose($readHandle);



📋 Practical Task

Build a Persistent Site Visit Counter

Your task is to create a script that tracks how many times a page has been visited, but without using a database.

Requirements:

  • Create a file named counter.txt (or let PHP create it automatically).
  • When the page loads, open the file in read mode to get the current number.
  • Increment that number by 1.
  • Open the file again in write mode ('w') to save the new total back to the file.
  • Display the message: "This page has been viewed X times."
  • Ensure you are using fclose() to properly close your file handles.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.