PHP file() Function: Syntax, Parameters, Return Value, and Usage Examples

This article explains PHP's file() function, detailing its syntax, parameters, return values, and provides multiple code examples for reading local and remote files, using flags and stream contexts, while noting memory considerations and alternative functions for large files.

php Courses
php Courses
php Courses
PHP file() Function: Syntax, Parameters, Return Value, and Usage Examples

PHP's file() function is a widely used file-reading function that reads the entire file into an array, with each element representing a line of the file.

The basic syntax is:

array file(string $filename, int $flags = 0, resource $context = null)

Parameters: $filename: the name of the file to read; can be a local path or a remote URL. $flags: optional flags that modify reading behavior, such as FILE_USE_INCLUDE_PATH, FILE_IGNORE_NEW_LINES, and FILE_SKIP_EMPTY_LINES. $context: optional stream context resource.

The function returns an array containing the file's lines, or false on failure.

Common usage examples:

1. Read a local file

$file_content = file('test.txt');

2. Read a remote file

$file_content = file('http://www.example.com/test.txt');

3. Use flag parameters

$file_content = file('test.txt', FILE_IGNORE_NEW_LINES);

4. Use a stream context

$context = stream_context_create(array('http' => array('header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)')));<br/>$file_content = file('http://www.example.com/test.txt', 0, $context);

Because file() loads the whole file into memory, it may cause memory overflow with very large files; in such cases, consider using fopen() and fgets() instead.

In summary, the file() function provides a convenient way to read file contents into an array, with customizable behavior via flags and context, but developers should be aware of its memory usage.

Recommended PHP learning resources:

Vue3+Laravel8+Uniapp Beginner to Real‑World Development Tutorial

Vue3+TP6+API Social E‑commerce System Development Course

Swoole From Beginner to Advanced Course

Workerman+TP6 Real‑time Chat System (Limited Offer)

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplefile-handlingFilestream contextflags
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.