PHP File Handling

PHP provides a set of built-in functions for file handling that allow you to create, open, read, write, and close files on the server. Here's a quick overview with examples:


Common File Handling Functions in PHP

Function Description
fopen() Opens a file or URL
fread() Reads from an open file
fwrite() Writes to an open file
fclose() Closes an open file
file_exists() Checks whether a file exists
filesize() Gets the size of a file
unlink() Deletes a file
file_get_contents() Reads entire file into a string
file_put_contents() Writes a string to a file

File Open Modes (Used inĀ fopen())

Mode Description
'r' Read only
'w' Write only, erases contents
'a' Write only, appends to file
'x' Write only, creates new file
'r+' Read/Write, pointer at beginning
'a+' Read/Write, pointer at end

Example: Creating and Writing to a File

<?php $filename = "example.txt"; $file = fopen($filename, "w"); // Open for writing if ($file) { fwrite($file, "Hello, World!\n"); fwrite($file, "This is a file handling example."); fclose($file); echo "File written successfully."; } else { echo "Unable to open file."; } ?>

Example: Reading from a File

<?php $filename = "example.txt"; if (file_exists($filename)) { $file = fopen($filename, "r"); $contents = fread($file, filesize($filename)); fclose($file); echo nl2br($contents); // Convert newlines to <br> for display } else { echo "File does not exist."; } ?>

Example: Reading/Writing the Whole File at Once

<?php file_put_contents("quick.txt", "This is quick file writing."); echo file_get_contents("quick.txt"); ?>