Working with the File System in PHP: Functions and Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with the File System in PHP: Basic Functions and Examples



Working with the file system is one of the key tasks in web development. PHP provides a powerful and flexible set of functions for creating, reading, writing, deleting files and folders, as well as for managing access rights. In this article, we will break down the main capabilities of PHP for working with the file system, provide practical examples, and look at typical errors.



1. Reading Files in PHP



PHP supports several ways to read data from files. The choice of method depends on the file size and the required level of control.



1.1. The file_get_contents() Function

The simplest way to read an entire file into a string is to use file_get_contents(). This function is suitable for small files (configurations, templates).



<?php// Reading the entire file into a string$content = file_get_contents('data.txt');if ($content !== false) {    echo "File content: " . htmlspecialchars($content);} else {    echo "Error reading file";}?>


1.2. The file() Function

If you need to get the file content as an array of strings (one line per element), use file().



<?php$lines = file('log.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);foreach ($lines as $lineNum => $line) {    echo "Line " . ($lineNum + 1) . ": " . htmlspecialchars($line) . "<br>";}?>


1.3. Line-by-line Reading with fopen() + fgets()

For large files (e.g., logs), it is better to use streaming reading to avoid holding the entire file in memory.



<?php$handle = fopen('large_file.csv', 'r');if ($handle) {    while (($buffer = fgets($handle, 4096)) !== false) {        echo $buffer . "<br>";    }    fclose($handle);} else {    echo "Could not open file";}?>


2. Writing Data to Files



Writing can also be done in different ways. The main difference is overwriting the file or appending to the end.



2.1. The file_put_contents() Function

A quick way to write a string to a file. If the file does not exist, it will be created. By default, the file is overwritten.



<?php$data = "New entry: " . date('Y-m-d H:i:s') . "";// Overwrite filefile_put_contents('log.txt', $data);// Append to the end (FILE_APPEND flag)file_put_contents('log.txt', $data, FILE_APPEND);?>


2.2. Manual Writing via fopen() + fwrite()

For fine-grained control (e.g., file locking), use the fopen() / fwrite() pair.



<?php$filename = 'counter.txt';$handle = fopen($filename, 'c+'); // 'c+' — creates the file if it doesn't existif (flock($handle, LOCK_EX)) { // exclusive lock    $current = (int) fread($handle, filesize($filename) ?: 1);    $current++;    ftruncate($handle, 0); // clear the file    rewind($handle);    fwrite($handle, $current);    flock($handle, LOCK_UN); // release the lock}fclose($handle);echo "Counter: $current";?>


3. Working with Directories



PHP allows you not only to manage files but also to create, delete, and browse folders.



3.1. Creating Folders (mkdir)

<?php// Create a single folderif (!is_dir('uploads')) {    mkdir('uploads', 0755);}// Recursive creation of nested folders (PHP 5.4+)mkdir('images/2024/12', 0755, true);?>


3.2. Deleting Folders (rmdir)

rmdir() only deletes an empty folder. To delete a folder with all its contents, a recursive function is needed.



<?phpfunction deleteDirectory($dir) {    if (!file_exists($dir)) {        return true;    }    if (!is_dir($dir)) {        return unlink($dir);    }    $items = array_diff(scandir($dir), ['.', '..']);    foreach ($items as $item) {                

Blogs

Book Recommendations