File System Operations

🐘 PHP Lesson 15 Advanced

PHP provides powerful functions to read, write, and manage files on the web server's storage drive.

1 Reading, Writing & Verifying File states

PHP provides convenient functions to read and write files directly in a single line, making it easy to manage files on the server:

  • file_put_contents(): Writes a string to a file, creating the file if it does not exist.
  • file_get_contents(): Reads the entire contents of a file into a string.
  • file_exists(): Verifies if a file exists on the server before trying to read it, preventing runtime errors.
2 File Operations Code

Let's run a program writing text to a file, verifying its existence, and reading it back:

PHP — File Operations ▶ Run Code
<?php
$file = "demo.txt";

// Write content to file
file_put_contents($file, "PHP File operations are simple and elegant!");

// Verify file exists before reading
if (file_exists($file)) {
    $content = file_get_contents($file);
    echo "File Content: " . $content . "\n";
} else {
    echo "Error: File does not exist!\n";
}
?>
3 Code Challenge
Challenge: Write a script that appends a log entry to a file named `log.txt` using the `FILE_APPEND` flag inside `file_put_contents()`. Read and print the file to verify the entry was appended.