PHP File Handling

In PHP, file handling is done using a set of built-in functions that allow you to create, open, read, write, and close files. Here's a quick overview of the key functions and examples for common file operations:


1. Opening a File

$handle = fopen("file.txt", "r"); // Modes: r, w, a, x, etc.
  • "r": Read only

  • "w": Write only (erases contents)

  • "a": Append

  • "x": Create and write only if file doesn't exist


2. Reading a File

$handle = fopen("file.txt", "r"); $content = fread($handle, filesize("file.txt")); fclose($handle); echo $content;

3. Writing to a File

$handle = fopen("file.txt", "w"); fwrite($handle, "Hello, World!"); fclose($handle);

4. Appending to a File

$handle = fopen("file.txt", "a"); fwrite($handle, "\nAppended text."); fclose($handle);

5. Checking if File Exists

if (file_exists("file.txt")) { echo "File exists."; } else { echo "File does not exist."; }

6. Deleting a File

if (file_exists("file.txt")) { unlink("file.txt"); echo "File deleted."; }

7. Reading File Line-by-Line

$handle = fopen("file.txt", "r"); while (!feof($handle)) { echo fgets($handle) . "<br>"; } fclose($handle);

8. Reading Entire File (Shortcut)

$content = file_get_contents("file.txt"); echo $content;

9. Writing to File (Shortcut)

file_put_contents("file.txt", "Quick write to file.");