file()

file() — Reads entire file into an array.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

You can use file_get_contents() to return the contents of a file as a string.

Signature

file(string $filename, int $flags = 0, ?resource $context = null): array|false

Parameters

ParameterTypeWhat it takes
$filenamestringPath to the file.
$flagsintThe optional parameter flags can be one, or more, of the following constants: FILE_USE_INCLUDE_PATH Search for the file in the include_path. FILE_IGNORE_NEW_LINES Omit newline at the end of each array element. FILE_SKIP_EMPTY_LINES Skip empty lines. FILE_NO_DEFAULT_CONTEXT Don't use the default context.
$context?resourceA context stream resource.

Return value

Returns the file in an array. Each element of the array corresponds to a line in the file, with the newline still attached. Upon failure, file() returns false. Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used. Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used. Note: Prior to PHP 8.1.0, the auto_detect_line_endings run-time configuration option could be enabled to help PHP properly recognize line endings when reading files created on Macintosh systems. This option has been deprecated as of PHP 8.1.0. If necessary, handle "\r" line breaks manually instead. Prior to PHP 8.1.0, the ...

Example

A runnable snippet:

// Get a file into an array. In this example we'll go through HTTP to get // the HTML source of a URL. $lines = file('http://www.example.com/'); // Loop through our array, show HTML source as HTML source; and line numbers too. foreach ($lines as $line_num => $line) { echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n"; } // Using the optional flags parameter $trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Changelog

VersionChange
8.3.0ValueError is thrown for any invalid values of flags.

See also

file_get_contents(), readfile(), fopen(), fsockopen(), popen(), stream_context_create()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page file() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.