PHP Filesystem

Beginner
9 min read
Updated: Nov 2026
4 examples
Paths, read, write & delete

Definition and Usage

The PHP filesystem functions let a script work with files and folders on the server. You can build a path, open a file, read or write its contents, check that it exists, and then delete or rename it.

Paths are handled with basename(), dirname(), and pathinfo(). A file is read or written step by step with fopen(), fread(), fwrite(), and fclose(), or in one call with file_get_contents() and file_put_contents().

Before touching a file, test it with file_exists(), is_file(), and is_dir(). Remove or move it with unlink() and rename().

This page explains the ideas. The Filesystem Functions index lists all 83 function guides.

Many file functions fail quietly.

Functions such as fopen() and file_get_contents() return false and raise a warning when a file is missing or not readable. Always compare the result with false before you use it.

Use __DIR__ for reliable paths.

A relative path depends on where PHP was started. __DIR__ . '/data.txt' always points next to the current script, no matter how it is run.

PHP Syntax

The everyday filesystem calls, from paths to deleting a file:

PHP
// 1. Paths
$file = __DIR__ . '/data.txt';          // file next to this script
basename($file);                        // "data.txt"
dirname($file);                         // the folder path
pathinfo($file);                        // dirname, basename, extension, filename

// 2. Open, read, write, close (stream style)
$h = fopen($file, 'r');                 // modes: r, w, a, x (+ b, +)
$text = fread($h, filesize($file));
fwrite($h, 'text');                     // needs 'w', 'a', or 'r+'
fclose($h);

// 3. Whole file in one call
$text  = file_get_contents($file);      // string, or false on failure
$bytes = file_put_contents($file, 'text', FILE_APPEND);

// 4. Check before you act
file_exists($file);                     // true for files and folders
is_file($file);                         // true only for a regular file
is_dir(__DIR__);                        // true only for a folder

// 5. Delete and move
unlink($file);                          // delete a file
rename($file, $newPath);                // rename or move

Core Ideas

What to remember when you work with files in PHP:

IdeaExampleRemember
Absolute and relative paths__DIR__ . '/data.txt'Relative paths depend on the working directory; __DIR__ does not
Split a pathbasename(), dirname(), pathinfo()These only work on the string; they do not check that the file exists
Open modes'r', 'w', 'a', 'x''w' empties the file, 'a' appends, 'x' fails if the file already exists
Stream handlefopen() → fclose()Check for false after opening, and close the handle when you are done
Read a line or a blockfgets($h), fread($h, $n)fgets() returns one line, fread() returns up to $n bytes
Read or write all at oncefile_get_contents(), file_put_contents()Shortest code for small files; add FILE_APPEND to add instead of replace
Existence checksfile_exists(), is_file(), is_dir()file_exists() is true for both files and folders
Delete and renameunlink(), rename()Return true or false; unlink() cannot remove a folder, use rmdir()

PHP Examples

Four short scripts that show how files are used in PHP. Run them from a folder where PHP is allowed to create files.

Example 1 — Work with paths

Split a path into its folder, file name, and extension. These functions work on the text, so the file does not need to exist.

PHP
<?php
$path = '/var/www/uploads/report.final.pdf';

echo basename($path) . "\n";
echo dirname($path) . "\n";

$info = pathinfo($path);
echo $info['extension'] . "\n";
echo $info['filename'] . "\n";

echo basename($path, '.pdf') . "\n";
?>

How It Works

  1. basename() returns the last part of the path, the file name with its extension.
  2. dirname() returns everything before the last slash, which is the folder.
  3. pathinfo() returns an array. The extension is the text after the last dot, and the filename is the name without it, so a name like report.final.pdf is split correctly.
  4. basename($path, '.pdf') removes the given suffix and gives the same name without the extension.

Example 2 — Write and read with fopen()

Open a file for writing, add two lines, close it, then read it back as a block and line by line.

PHP
<?php
$file = __DIR__ . '/notes.txt';

// Write
$h = fopen($file, 'w');
if ($h === false) {
    exit('Cannot open file for writing');
}
fwrite($h, "Line one\n");
fwrite($h, "Line two\n");
fclose($h);

// Read all at once
$h = fopen($file, 'r');
echo fread($h, filesize($file));
fclose($h);

// Read line by line
$h = fopen($file, 'r');
$n = 0;
while (($line = fgets($h)) !== false) {
    $n++;
    echo $n . ': ' . $line;
}
fclose($h);
?>
fopen() Tutorial

How It Works

  1. fopen($file, 'w') creates the file, or empties it if it exists, and returns a handle. The === false check stops the script when the folder is not writable.
  2. fwrite() sends text to the handle. The \n ends each line, and fclose() flushes the data and releases the file.
  3. fread($h, filesize($file)) reads the whole file in one block, because the length passed is the file size.
  4. fgets() returns one line each time, including its newline, and returns false at the end of the file, which ends the while loop.

Example 3 — file_put_contents() and file_get_contents()

Write a file, append to it, and read it all back without managing a handle.

PHP
<?php
$file = __DIR__ . '/greeting.txt';

file_put_contents($file, "Hello\n");

$bytes = file_put_contents($file, "World\n", FILE_APPEND);
echo $bytes . "\n";

$text = file_get_contents($file);
if ($text === false) {
    exit('Cannot read file');
}
echo $text;
?>

How It Works

  1. file_put_contents($file, "Hello\n") creates the file and replaces anything already in it.
  2. FILE_APPEND adds the next text to the end instead of replacing the file. The call returns the number of bytes written, which is 6 for World plus the newline.
  3. file_get_contents() returns the whole file as one string, or false if it cannot be read, so the result is checked before it is printed.

Example 4 — Check, rename and delete

Create a small folder and file, test them, move the file to a new name, and clean everything up.

PHP
<?php
$dir = __DIR__ . '/tmp-demo';
if (!is_dir($dir)) {
    mkdir($dir);
}

$a = $dir . '/a.txt';
$b = $dir . '/b.txt';
file_put_contents($a, 'hi');

var_dump(file_exists($a));
var_dump(is_file($a));
var_dump(is_dir($dir));
var_dump(is_dir($a));

rename($a, $b);
var_dump(file_exists($a));

unlink($b);
rmdir($dir);
echo file_exists($b) ? "still there\n" : "deleted\n";
?>
unlink() Tutorial

How It Works

  1. is_dir($dir) avoids a warning from mkdir() when the folder already exists.
  2. file_exists() and is_file() are both true for a.txt. is_dir() is true for the folder and false for the file.
  3. rename($a, $b) gives the file a new name, so a.txt no longer exists.
  4. unlink() deletes the file and rmdir() removes the now-empty folder, so the last check prints deleted.

Next: PHP Filesystem Functions Index

After you know paths, streams, and file checks, open the function index for all 83 guides.

Start withWhy
basename()Get the file name from a path
fopen()Open a file and get a handle
file_get_contents()Read a whole file into a string
file_put_contents()Write a string to a file
file_exists()Check whether a file or folder exists
unlink()Delete a file

Full list: PHP Filesystem Functions index (/php/file-system/function).

Frequently Asked Questions

The PHP filesystem functions let a script work with files and folders on the server: build and split paths, open and read files, write data, check whether something exists, and delete, rename, or copy files. They are built into PHP and need no extra library.
file_get_contents() reads a whole file into one string in a single call, which is ideal for small files. fopen() returns a handle that you read or write step by step with fgets(), fread(), or fwrite(), so it suits large files, appending, and line-by-line processing. Always release the handle with fclose().
A relative path such as data.txt is resolved against the current working directory, which can change depending on how the script is started. __DIR__ is the folder of the current file, so __DIR__ . '/data.txt' always points to the same place. Use realpath() when you need the cleaned-up absolute path.
Use file_exists() to test whether a path exists at all, is_file() to make sure it is a regular file, and is_dir() to make sure it is a folder. Also test the return value of fopen() and file_get_contents(), because they return false when the read fails, for example because of permissions.
Call unlink($path) to delete a file and rename($old, $new) to rename or move it. Both return true on success and false on failure. To remove an empty folder use rmdir(), and use copy() when you want to keep the original.
Practice the examples here, then open the Filesystem Functions index for all 83 function guides, grouped into path helpers, streams, file information, existence checks, uploads, links, and directories.

Browse every filesystem function

Open the functions index for categorized guides with examples and FAQs.

Filesystem Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful