Back to course

Introduction to File System Operations (Reading/Writing Files)

PHP: The Complete 0 to Hero Bootcamp

42. Introduction to File System Operations

PHP is often used to interact with the server's filesystem, managing files, logs, and configuration data.

1. Reading Files (file_get_contents)

The simplest way to read an entire file into a string.

php

<?php $filename = "data.txt"; // Assume data.txt contains: Hello World if (file_exists($filename)) { $content = file_get_contents($filename); echo "File Content: " . $content; } else { echo "Error: File not found."; } ?>

2. Writing to Files (file_put_contents)

Writes a string to a file. If the file doesn't exist, it is created. By default, it overwrites the content.

php

<?php $new_data = "This is a new line."; // Overwrite existing content file_put_contents("log.txt", $new_data); // Append (add to the end) using a flag file_put_contents("log.txt", "\nAnother log entry.", FILE_APPEND); ?>

3. Advanced File Handling (Opening Streams)

For large files or precise control, we use fopen(), fwrite(), and fclose().

FunctionDescription
fopen($file, $mode)Opens the file stream in a specific mode (w=write, a=append, r=read).
fwrite($handle, $string)Writes content to the open file.
fgets($handle)Reads a single line from the file.
fclose($handle)Closes the file stream, releasing server resources.

php

<?php $file = fopen("temp.txt", "w"); fwrite($file, "Writing stream data."); fclose($file); ?>