Skip to content
PHP

Read and Write Files in PHP

Read, write, append, and iterate files with PHP filesystem functions.

By EZ4Code Team
fileiointermediate

Code

<?php

// Read entire file
$content = file_get_contents("data.txt");
echo $content;

// Read lines into array
$lines = file("data.txt", FILE_IGNORE_NEW_LINES);

// Write file
file_put_contents("output.txt", "Hello\n");

// Append
file_put_contents("log.txt", "New entry\n", FILE_APPEND);

// Open / read / close
$handle = fopen("data.txt", "r");
while (($line = fgets($handle)) !== false) {
    echo trim($line);
}
fclose($handle);

// Check file
if (file_exists("data.txt")) {
    echo filesize("data.txt");
}

// Directory listing
foreach (glob("*.txt") as $file) {
    echo $file;
}

Explanation

file_get_contents reads an entire file, while file() loads lines into an array and fopen/fgets allows line-by-line iteration. file_put_contents with FILE_APPEND adds content without overwriting. glob() pattern-matches filenames, and file_exists checks presence before reading.

More PHP Snippets