What is it?
PHP can read and write files on the server's filesystem. This enables log files, config files, CSV exports, file uploads, and caching without a database.
Why does it matter?
Not everything belongs in a database. Application logs, generated reports, uploaded images, and temporary caches are all managed through PHP's file functions.
Learn reading and writing files in PHP — file_get_contents, file_put_contents, fopen, fwrite.
Real-World Use Cases
- 📋 Application logging - Append each error or event to a log.txt file using file_put_contents with FILE_APPEND for debugging.
- 📊 CSV export - Write report data row by row to a CSV file so users can download it in Excel.
- ⚙️ Config file reading - Read a JSON or INI config file at startup using file_get_contents and json_decode.
- 🖼️ Upload processing - Move an uploaded image to a permanent directory, check its type, and resize it.
file_get_contents and file_put_contents
$data = file_get_contents("file.txt");
echo $data;
file_put_contents("file.txt", "Hello World");
#append mode
file_put_contents("file.txt", "New Line\n", FILE_APPEND);
fopen for More Control
$handle = fopen("file.txt", "r");
$content = fread($handle, filesize("file.txt"));
fclose($handle);
File Checks and Management
// Read line by line
if (file_exists($file)) {
$handle = fopen($file, "r");
if ($handle) {
echo "Reading with fopen:\n";
while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);
}
}
// Write using fopen
$handle = fopen($file, "a");
if ($handle) {
fwrite($handle, "Written using fopen\n");
fclose($handle);
}
// Exists
if (file_exists($file)) {
echo "\nFile exists\n";
}
// Permissions
if (is_readable($file)) {
echo "File is readable\n";
}
if (is_writable($file)) {
echo "File is writable\n";
}
// Size
echo "File size: " . filesize($file) . " bytes\n";
// Rename
rename($file, "new_file.txt");
// Delete (uncomment to use)
// unlink("new_file.txt");
$logFile = "app.log";
if (!file_exists($logFile)) {
file_put_contents($logFile, "");
}
$message = date("Y-m-d H:i:s") . " - User logged in\n";
file_put_contents($logFile, $message, FILE_APPEND);
Q: When should I use fopen instead of fle_get_contents?
Use file_get_contents for simple one-shot reads. Use fopen for large files you need to read line-by-line (saving memory), or when you need both reading and writing in the same operation.
Comments (0)
No comments yet. Be the first!
Leave a Comment