📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners File Handling

File Handling

5 min read
PHP can read and write files using file_get_contents(), file_put_contents(), and fopen(). This is useful for logs, config files, and processing uploads. Always validate file paths from user input to prevent security issues.

File Handling

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

// Write to file
file_put_contents("data.txt", "Hello!");
file_put_contents("data.txt", "more\n", FILE_APPEND);

// Read line by line
$lines = file("data.txt");         // array of lines
$handle = fopen("data.txt", "r");
while (!feof($handle)) {
    $line = fgets($handle);
}
fclose($handle);

// File info
file_exists("data.txt");  // true/false
filesize("data.txt");     // bytes
filemtime("data.txt");    // last modified timestamp
is_readable("data.txt");
is_writable("data.txt");

// File operations
copy("src.txt", "dest.txt");
rename("old.txt", "new.txt");
unlink("delete.txt");    // delete file
mkdir("folder", 0755, true);
rmdir("folder");