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.
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.
Syntax
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
Reference
Core Ideas
What to remember when you work with files in PHP:
Idea
Example
Remember
Absolute and relative paths
__DIR__ . '/data.txt'
Relative paths depend on the working directory; __DIR__ does not
Split a path
basename(), 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 handle
fopen() → fclose()
Check for false after opening, and close the handle when you are done
Read a line or a block
fgets($h), fread($h, $n)
fgets() returns one line, fread() returns up to $n bytes
Read or write all at once
file_get_contents(), file_put_contents()
Shortest code for small files; add FILE_APPEND to add instead of replace
Existence checks
file_exists(), is_file(), is_dir()
file_exists() is true for both files and folders
Delete and rename
unlink(), rename()
Return true or false; unlink() cannot remove a folder, use rmdir()
Code
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.
report.final.pdf
/var/www/uploads
pdf
report.final
report.final
How It Works
basename() returns the last part of the path, the file name with its extension.
dirname() returns everything before the last slash, which is the folder.
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.
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($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.
fwrite() sends text to the handle. The \n ends each line, and fclose() flushes the data and releases the file.
fread($h, filesize($file)) reads the whole file in one block, because the length passed is the file size.
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.
file_put_contents($file, "Hello\n") creates the file and replaces anything already in it.
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.
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.
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.