Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

fopen

Opens a file for reading or writing piece by piece.

Syntax

fopen(string $filename, string $mode): resource|false

Parameters

ParameterTypeDescription
$filenamestringThe path to the file.
$modestringThe mode: `r` reads, `w` writes and truncates, `a` appends.

Return value

resource|falseA file handle, or `false` on failure.

Examples

Reading a file line by line:

<?php
 
$file = sys_get_temp_dir() . '/ref-fopen.txt';
file_put_contents($file, "first\nsecond\n");
 
$handle = fopen($file, 'r');
 
while (($line = fgets($handle)) !== false) {
    echo strtoupper(rtrim($line)), "\n";
}
 
fclose($handle);

Output:

FIRST
SECOND

Writing piece by piece:

<?php
 
$file = sys_get_temp_dir() . '/ref-fwrite.txt';
 
$handle = fopen($file, 'w');
fwrite($handle, "one\n");
fwrite($handle, "two\n");
fclose($handle);
 
echo file_get_contents($file);

Output:

one
two

Notes

This is how large files are read: only one line is in memory at any moment. An opened file must be closed with fclose().

See also

  • file_get_contents — Reads a whole file into a string.
  • fgetcsv — Reads a line of a CSV file and splits it into fields.
  • file — Reads a file into an array of lines.

Related recipes

In the tutorial

  • Reading and writing files — Working with files in PHP — writing, reading, appending, reading line by line, checking existence and deleting.

Thanks for reading!

Donate to the site — we work hard for you.