Lesson 12 of 20

File Handling

Reading and Writing Files

PHP provides simple functions for file operations — reading, writing, appending, and more.

Example
<?php
// Write to file
file_put_contents('data.txt', "Hello, File!\n");

// Append to file
file_put_contents('data.txt', "New line\n", FILE_APPEND);

// Read entire file as string
$content = file_get_contents('data.txt');
echo $content;

// Read file as array of lines
$lines = file('data.txt', FILE_IGNORE_NEW_LINES);
foreach ($lines as $line) {
    echo $line . "\n";
}

// Check if file exists
if (file_exists('data.txt')) {
    echo "File size: " . filesize('data.txt') . " bytes";
}

// JSON file handling
$data = ['name' => 'Alice', 'age' => 25];
file_put_contents('user.json', json_encode($data, JSON_PRETTY_PRINT));

$user = json_decode(file_get_contents('user.json'), true);
echo $user['name']; // "Alice"
?>