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
Arrays and Array Functions in PHP
Create indexed, associative, and multidimensional arrays with map and filter.
String Functions in PHP
Manipulate strings with substr, replace, explode, and sprintf in PHP.
PDO Database Queries in PHP
Connect and run prepared statements safely with PDO in PHP.
Sessions and Cookies in PHP
Store user data across requests with sessions and cookies in PHP.
Classes and Inheritance in PHP
Define classes with constructors, visibility, and inheritance in PHP.