PHP File Advanced Operations 🔐
The Secret Vault Story
Imagine you have a magic diary that everyone in your family wants to write in at the same time. What happens? Chaos! Words get mixed up, pages get messy.
That’s exactly what happens when multiple programs try to use the same file at once. But PHP has superpowers to handle this!
1. File Locking 🔒
What is File Locking?
Think of file locking like putting a “DO NOT DISTURB” sign on your bedroom door.
When you lock a file:
- You’re telling everyone: “I’m using this file right now!”
- Others must wait until you’re done
- No messy mix-ups happen
The Two Types of Locks
// SHARED LOCK (Reading)
// Like saying: "I'm just looking!"
flock($file, LOCK_SH);
// EXCLUSIVE LOCK (Writing)
// Like saying: "Don't touch - I'm changing things!"
flock($file, LOCK_EX);
Real Example: Safe File Writing
$file = fopen("scores.txt", "a");
// Lock it (exclusive - writing)
flock($file, LOCK_EX);
// Now safe to write!
fwrite($file, "New Score: 100\n");
// Unlock it
flock($file, LOCK_UN);
fclose($file);
Lock Types Quick Guide
| Lock Type | Constant | Use When |
|---|---|---|
| Shared | LOCK_SH |
Reading only |
| Exclusive | LOCK_EX |
Writing |
| Unlock | LOCK_UN |
Done! |
| Non-blocking | LOCK_NB |
Don’t wait |
Non-Blocking Lock Example
$file = fopen("data.txt", "w");
// Try to lock, but don't wait forever
if (flock($file, LOCK_EX | LOCK_NB)) {
fwrite($file, "Hello!");
flock($file, LOCK_UN);
} else {
echo "File is busy!";
}
fclose($file);
2. Stream Wrappers 🌊
What are Stream Wrappers?
Imagine you have a magic remote control that works on:
- Your TV at home (local files)
- Your friend’s TV across town (FTP files)
- A TV on the internet (HTTP files)
Same remote, different TVs!
Stream wrappers let you use the same PHP functions to access different types of data.
Built-in Stream Wrappers
graph TD A["PHP Stream Functions"] --> B["file://"] A --> C["http://"] A --> D["ftp://"] A --> E["php://"] A --> F["data://"] B --> B1["Local Files"] C --> C1["Web Pages"] D --> D1["FTP Servers"] E --> E1["PHP I/O"] F --> F1["Inline Data"]
Examples of Each Wrapper
file:// - Local Files (default)
// These are the same!
$data = file_get_contents("myfile.txt");
$data = file_get_contents("file://myfile.txt");
http:// - Web Pages
// Read a web page!
$html = file_get_contents("http://example.com");
echo $html;
php://input - Raw POST Data
// Get raw JSON from a request
$json = file_get_contents("php://input");
$data = json_decode($json, true);
php://memory - Temporary Storage
// Write to memory (super fast!)
$mem = fopen("php://memory", "r+");
fwrite($mem, "Stored in RAM!");
rewind($mem);
echo fread($mem, 100);
fclose($mem);
data:// - Inline Data
// Data right in the URL!
$text = file_get_contents(
"data://text/plain,Hello World!"
);
echo $text; // Hello World!
Stream Context: Extra Settings
// Create special settings
$options = [
'http' => [
'method' => 'GET',
'timeout' => 5
]
];
$context = stream_context_create($options);
// Use settings when fetching
$page = file_get_contents(
"http://example.com",
false,
$context
);
3. Temporary Files 📝
What are Temporary Files?
Think of temporary files like scratch paper.
- You write notes on it
- You use it for a moment
- Then it disappears when you’re done!
Why Use Temporary Files?
| Reason | Example |
|---|---|
| Processing big data | Sorting millions of records |
| Uploads | Holding file before saving |
| Caching | Quick storage |
| Safety | Test before saving |
Creating Temporary Files
Method 1: tmpfile() - Auto-delete!
// Creates temp file that vanishes
// when you close it!
$temp = tmpfile();
fwrite($temp, "Secret notes...");
rewind($temp);
echo fread($temp, 100);
fclose($temp); // Poof! Gone!
Method 2: tempnam() - You control it
// Create in system temp folder
$path = tempnam(sys_get_temp_dir(), "myapp_");
file_put_contents($path, "My data");
// Use it...
// Delete when done
unlink($path);
Finding the Temp Folder
// Get system temp directory
$tempDir = sys_get_temp_dir();
echo $tempDir;
// Windows: C:\Users\You\AppData\Local\Temp
// Linux: /tmp
Real-World Example: File Upload
// Temp file for upload processing
$temp = tmpfile();
$meta = stream_get_meta_data($temp);
$tempPath = $meta['uri'];
// Write uploaded data
fwrite($temp, $_FILES['upload']['tmp_name']);
// Process it safely...
// If all good, save permanently
if ($isValid) {
copy($tempPath, "uploads/final.jpg");
}
fclose($temp); // Temp file gone!
Putting It All Together 🎯
Here’s a complete example using ALL three concepts:
// 1. Create a temporary file
$temp = tmpfile();
// 2. Lock it for safe writing
flock($temp, LOCK_EX);
// 3. Use stream wrapper to get web data
$data = file_get_contents(
"http://api.example.com/data"
);
// 4. Write to temp file
fwrite($temp, $data);
// 5. Unlock
flock($temp, LOCK_UN);
// 6. Read back
rewind($temp);
$content = fread($temp, 10000);
// 7. Close (auto-deletes!)
fclose($temp);
Quick Summary 📌
graph TD A["File Advanced Operations"] --> B["🔒 File Locking"] A --> C["🌊 Stream Wrappers"] A --> D["📝 Temporary Files"] B --> B1["LOCK_SH - Share"] B --> B2["LOCK_EX - Exclusive"] B --> B3["LOCK_UN - Unlock"] C --> C1["file://"] C --> C2["http://"] C --> C3["php://"] D --> D1["tmpfile - Auto-delete"] D --> D2["tempnam - You control"]
Remember! 💡
- File Locking = Putting a sign on the door
- Stream Wrappers = One remote for all TVs
- Temporary Files = Scratch paper that disappears
You’ve got this! These tools help PHP programs work safely and smartly with files. 🚀
