PHP Manual

PHP function fopen()

22. 08. 2019

Obsah článku

The `fopen()` function represents low-level access to files on disk.

The programmer has to do everything himself (opening the file, reading the data, writing new data, closing the file).

If you just need to read and write files quickly, there are simpler options:

Basic usage

$text = 'Any text to be saved...';
$file = fopen('file.html', 'a+'); // Opens file and mode
fwrite($file, $text); // Saves to file
fclose($file); // Closes the file

If we open a file for reading and it is not closed, no other process can access it!

Types of file handling modes

We can work with files in different modes, which tell information about access rights.

For example, if we want to open a file for read-only, then the r mode is sufficient.

If we open the file for writing, then it will be marked as open on disk and another process (script) will not be able to write to it until we close it again. This ensures that the file will not be corrupted during writing.

Mode Meaning
and Opens the file, if it does not exist it will be created
a+ Opens a file to add data and or read data, if it does not exist it will be created
r Open read-only
r+
w Open for writing, the original data will be deleted and replaced with new data, if it does not exist it will be created
w+ Open for write and read, original data will be deleted and replaced with new data, if it does not exist it will be created

Jan Barášek   Více o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Související články

1.
3.
Status:
All systems normal.
2024