PHP
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
34: File Handling in PHP
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.
There are no comments for now.