File Reading and Writing

Back

Loading concept...

📂 PHP File System Operations: Reading & Writing Files

The Story of the Magic Filing Cabinet

Imagine you have a magic filing cabinet in your room. This cabinet can store notes, drawings, and all kinds of information. But here’s the thing — you can’t just grab papers from it randomly. You need to:

  1. Open the drawer (File Opening)
  2. Read what’s inside (File Reading)
  3. Write new stuff (File Writing)
  4. Close the drawer (File Closing)

PHP works exactly like this with files! Let’s learn how to be the master of your magic filing cabinet.


🚪 File Opening — Unlocking the Drawer

Before you can read or write anything, you must open the file first. It’s like turning a key to unlock a drawer.

The fopen() Function

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

Think of it like this:

  • "story.txt" = The name of the drawer
  • "r" = The mode (what you want to do)

Opening Modes — The Keys

Mode What It Does Like…
"r" Read only Looking at notes
"w" Write (erases old) Fresh paper
"a" Append (add to end) Adding more notes
"r+" Read and write Edit your notes
// Open for reading
$file = fopen("diary.txt", "r");

// Open for writing (starts fresh!)
$file = fopen("diary.txt", "w");

// Open to add more (keeps old stuff)
$file = fopen("diary.txt", "a");

Remember: If the drawer doesn’t exist and you use "w" or "a", PHP creates it for you! Magic! ✨


👀 File Reading — Looking at What’s Inside

Now that the drawer is open, let’s see what’s in there!

Reading Line by Line with fgets()

Imagine reading a book, one line at a time:

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

// Read one line
$line = fgets($file);
echo $line;

fclose($file);

Reading All Lines — The Loop

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

while (!feof($file)) {
    $line = fgets($file);
    echo $line . "<br>";
}

fclose($file);

What’s feof()? It checks if we reached the End Of File — like knowing when you’ve read the last page!

Reading Character by Character with fgetc()

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

while (!feof($file)) {
    $char = fgetc($file);
    echo $char;
}

fclose($file);

Reading a Chunk with fread()

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

// Read first 100 characters
$content = fread($file, 100);
echo $content;

fclose($file);

✏️ File Writing — Adding Your Notes

Time to write your own story in the magic cabinet!

Writing with fwrite()

$file = fopen("myfile.txt", "w");

fwrite($file, "Hello, World!");
fwrite($file, "\nThis is line 2!");

fclose($file);

What happens:

  1. Opens myfile.txt (creates it if missing)
  2. Writes “Hello, World!”
  3. Writes another line
  4. Closes the file

Adding to Existing Content (Append Mode)

$file = fopen("diary.txt", "a");

fwrite($file, "\nToday was fun!");

fclose($file);

Using "a" mode = Your old notes stay safe, new notes go at the end!

graph TD A["Open File"] --> B{Which Mode?} B -->|w| C["Erase &amp; Write Fresh"] B -->|a| D["Keep Old + Add New"] B -->|r+| E["Read &amp; Edit"] C --> F["Write Content"] D --> F E --> F F --> G["Close File"]

🔐 File Closing — Lock the Drawer

Always close what you open! It’s like putting toys away after playing.

The fclose() Function

$file = fopen("data.txt", "r");
// ... do stuff with the file ...
fclose($file);

Why close files?

  • Saves memory
  • Lets other programs use the file
  • Makes sure all data is saved properly

🚀 The Easy Way: file_get_contents()

Don’t want to open, read, close manually? Use the magic shortcut!

// Read entire file in ONE line!
$content = file_get_contents("story.txt");
echo $content;

That’s it! No fopen(), no fclose() — PHP handles everything!

Reading from the Internet Too!

$webpage = file_get_contents("https://example.com");
echo $webpage;

file_get_contents() is like:

  • Asking a friend to grab your notes and read them to you
  • One simple request, everything done!

💾 The Easy Way: file_put_contents()

Writing made super simple!

// Write to file in ONE line!
file_put_contents("notes.txt", "Hello!");

Add to File (Don’t Erase!)

file_put_contents(
    "notes.txt",
    "\nNew line!",
    FILE_APPEND
);

The FILE_APPEND flag = “Add this to the end, don’t erase!”

graph TD A["Need to Read?"] --> B["file_get_contents"] B --> C["Get All Content"] D["Need to Write?"] --> E["file_put_contents"] E --> F{Want to Add?} F -->|Yes| G["Use FILE_APPEND"] F -->|No| H["Replace Content"]

❓ File Existence Checks — Is the Drawer There?

Before opening a drawer, make sure it exists!

Check with file_exists()

if (file_exists("treasure.txt")) {
    echo "Found the treasure!";
} else {
    echo "No treasure here...";
}

Check If It’s Really a File

if (is_file("data.txt")) {
    echo "Yes, it's a file!";
}

Check If Readable/Writable

// Can I read it?
if (is_readable("secret.txt")) {
    echo "I can read this!";
}

// Can I write to it?
if (is_writable("notes.txt")) {
    echo "I can write here!";
}

Safe Reading Pattern

$filename = "mydata.txt";

if (file_exists($filename) && is_readable($filename)) {
    $content = file_get_contents($filename);
    echo $content;
} else {
    echo "Cannot read file!";
}

📊 File Information — What’s This Drawer Like?

Want to know more about your files? PHP can tell you everything!

File Size with filesize()

$size = filesize("photo.jpg");
echo "Size: " . $size . " bytes";

When Was It Changed? filemtime()

$time = filemtime("document.txt");
echo "Last modified: " . date("Y-m-d", $time);

Get Everything with stat()

$info = stat("myfile.txt");

echo "Size: " . $info['size'];
echo "Last access: " . $info['atime'];
echo "Last modified: " . $info['mtime'];

Quick Info Table

Function What It Tells You
filesize() How big (bytes)
filemtime() When last changed
fileatime() When last opened
filetype() File or directory?
// Complete example
$file = "report.txt";

if (file_exists($file)) {
    echo "Name: " . $file;
    echo "Size: " . filesize($file) . " bytes";
    echo "Type: " . filetype($file);
    echo "Modified: " . date("M d, Y", filemtime($file));
}

🎯 Quick Summary

graph TD A["PHP File Operations"] --> B["Manual Way"] A --> C["Easy Way"] B --> D["fopen"] D --> E["fread/fgets"] D --> F["fwrite"] E --> G["fclose"] F --> G C --> H["file_get_contents"] C --> I["file_put_contents"] A --> J["Check First"] J --> K["file_exists"] J --> L["is_readable"] J --> M["is_writable"] A --> N["Get Info"] N --> O["filesize"] N --> P["filemtime"] N --> Q["stat"]

🌟 The Golden Rules

  1. Always close files you open with fopen()
  2. Check if files exist before reading
  3. Use the easy functions (file_get_contents, file_put_contents) for simple tasks
  4. Choose the right mode"r" to read, "w" to write fresh, "a" to add

Now you’re the master of PHP’s magic filing cabinet! Go forth and organize your data like a pro! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.