Working with the File System in PHP: A Complete Guide for Beginners

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

Introduction: Why Does PHP Need to Work with Files?

Any web project will sooner or later face the need to save data on the server. Whether it's uploading a user avatar, creating error logs, or generating reports — all of this requires the ability to manage files and folders. PHP provides a powerful set of functions for working with the file system, and mastering them is not as difficult as it seems.

In this article, we will cover the basic operations: creating, reading, writing, deleting files and directories, as well as checking access permissions. All examples are written in pure PHP and are ready to use in your projects.



1. Basics: Opening, Reading, and Writing Files

Before doing anything with a file, you need to open it. For this, PHP uses the fopen() function. It returns a resource (a file pointer) that you can then work with.



File Opening Modes

The second parameter of fopen() is the access mode. Here are the most popular ones:

  • 'r' — read-only, pointer at the beginning of the file.
  • 'w' — write (creates the file or truncates an existing one).
  • 'a' — append to the end of the file (creates it if it doesn't exist).
  • 'x' — create and write; if the file already exists, an error occurs.


Example: Writing Text to a File

<?php$filename = 'test.txt';$file = fopen($filename, 'w') or die('Could not open file');$text = "Hello, world!";fwrite($file, $text);fclose($file);echo 'File written successfully';?>

After writing, always close the file with the fclose() function — this frees up system resources.



Reading a File Line by Line

<?php$file = fopen('test.txt', 'r');while (!feof($file)) {    $line = fgets($file);    echo $line . '<br>';}fclose($file);?>

The feof() function checks if the end of the file has been reached. fgets() reads one line.



Simpler Alternatives

For quick operations, PHP offers wrapper functions:

  • file_get_contents($filename) — reads the entire file into a string.
  • file_put_contents($filename, $data) — writes a string to a file (creates or overwrites).
<?php// Reading$content = file_get_contents('test.txt');echo $content;

// Writingfile_put_contents('new.txt', 'Simple write');?>


2. Managing Directories: Creating, Deleting, Navigating

Working with folders in PHP is almost as simple as working with files. The main functions are mkdir(), rmdir(), and scandir().



Creating a Folder

<?php$dir = 'uploads';if (!is_dir($dir)) {    mkdir($dir, 0777, true);    echo 'Folder created';} else {    echo 'Folder already exists';}?>

The parameter 0777 is the access permissions (mask). The third argument true allows creating nested directories recursively (e.g., images/2024/).



Deleting a Folder

The rmdir() function only deletes an empty directory. If there are files inside, you need to clear it first:

<?phpfunction removeDir($dir) {    if (!is_dir($dir)) return;    $items = scandir($dir);    foreach ($items as $item) {        if ($item == '.' || $item == '..') continue;        $path = $dir . '/' . $item;        if (is_dir($path)) {            removeDir($path);        } else {            unlink($path);        }    }    rmdir($dir);}removeDir('temp');echo 'Folder deleted';?>


Getting a List of Files in a Folder

<?php$files = scandir('uploads');foreach ($files as $file) {    if ($file != '.' && $file != '..') {        echo $file . '<br>';    }}?>


3.

Blogs

Book Recommendations