</>
Skip to content
PHP lessons (28/49)

PHP — File Handling

Reading files

<?php
// Read entire file
$content = file_get_contents('file.txt');

// Read line by line
$lines = file('file.txt');

// Read with fopen
$handle = fopen('file.txt', 'r');
while (($line = fgets($handle)) !== false) {
    echo $line;
}
fclose($handle);
?>

Writing files

<?php
// Write entire file
file_put_contents('output.txt', 'Hello, World!');

// Append
file_put_contents('output.txt', "\nSecond line", FILE_APPEND);

// Write with fopen
$handle = fopen('output.txt', 'w');
fwrite($handle, "Line 1\n");
fwrite($handle, "Line 2\n");
fclose($handle);
?>

File operations

<?php
// Check existence
if (file_exists('file.txt')) {
    echo 'File exists';
}

// Get file info
echo filesize('file.txt');
echo date('Y-m-d H:i:s', filemtime('file.txt'));

// Copy, rename, delete
copy('file.txt', 'copy.txt');
rename('copy.txt', 'renamed.txt');
unlink('renamed.txt');
?>

Directory operations

<?php
// Create directory
mkdir('newdir', 0755, true);

// List files
$files = scandir('.');
foreach ($files as $file) {
    echo $file . "\n";
}

// Delete directory
rmdir('newdir');
?>

CSV files

<?php
// Read CSV
$handle = fopen('data.csv', 'r');
while (($row = fgetcsv($handle)) !== false) {
    print_r($row);
}
fclose($handle);

// Write CSV
$handle = fopen('output.csv', 'w');
fputcsv($handle, ['Name', 'Age', 'Email']);
fputcsv($handle, ['Alice', 30, 'alice@example.com']);
fclose($handle);
?>

Mini Practice

Write PHP code that:

  1. Reads a file line by line
  2. Writes data to a CSV file
  3. Checks file existence and size
  4. Lists files in a directory

Up Next

In the next lesson, you'll learn about Sessions — managing user sessions.

Related Topics

Frequently Asked Questions about File Handling

What is File Handling in PHP?

File Handling is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn File Handling?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn File Handling.

Why is File Handling important in PHP?

File Handling is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.