Backend Development 5 min read

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:

<code>array file(string $filename, int $flags = 0, resource $context = null)</code>

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

<code>$file_content = file('test.txt');</code>

2. Read a remote file

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

3. Use flag parameters

<code>$file_content = file('test.txt', FILE_IGNORE_NEW_LINES);</code>

4. Use a stream context

<code>$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);</code>

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)

Backend DevelopmentPHPCode Examplefile handlingfile()stream 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

login 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.