PHP file() Function

Summary: in this tutorial, you will learn how to use the PHP file() function to read the entire file into an array.

Introduction to the PHP file() function #

The file() function reads an entire file specified by a $filename into an array:

file ( string $filename , int $flags = 0 , resource $context = ? ) : arrayCode language: PHP (php)

The file() function has three parameters:

  • $filename is the path to the file.
  • $flags is an optional parameter that can be one or more of the constants below.
  • $context is a valid stream context resource.

The following table shows the values for the $flags:

FlagMeaning
FILE_USE_INCLUDE_PATHSearch for the file in the include path.
FILE_IGNORE_NEW_LINESSkip the newline at the end of the array element.
FILE_SKIP_EMPTY_LINESSkip empty lines in the file.

The file() function returns an array in which each element corresponds to a line of the file. If you don’t want to include the newline character in each array element, you can use the FILE_IGNORE_NEW_LINES flag.

To skip empty lines, you can use the FILE_SKIP_EMPTY_LINES option.

Note that the file() function also works with a remote file using the HTTP or FTP protocol.

To read the entire file into a string, you can use the file_get_contents() function.

PHP file() function example #

The following example uses the file() function to read the robots.txt file from the php.net into an array and display its contents line by line:

<?php

$lines = file(
    'https://www.php.net/robots.txt',
    FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES
);


if ($lines) {
    foreach ($lines as $line) {
        echo htmlspecialchars($line) . PHP_EOL;
    }
}Code language: HTML, XML (xml)

If you run the script behind a proxy, it won’t work and issue the following error:

Warning: file(http://www.php.net/robots.txt): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respon in ...\file.php on line 5Code language: plaintext (plaintext)

To fix it, you need to create a new stream context and set the proxy like this:

<?php

$options = [
    'http'=>[
      'method'=>"GET",
      'header'=>"Accept-language: en\r\n",
      'proxy'=>"tcp://<proxy_ip>:<proxy_port>"
    ]
];

$context = stream_context_create($options);

$lines = file(
    'https://www.php.net/robots.txt',
    FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES,
    $context
);


if ($lines) {
    foreach ($lines as $line) {
        echo htmlspecialchars($line) . PHP_EOL;
    }
}Code language: HTML, XML (xml)

In this code, you need to replace the <proxy_ip> and <proxy_port> with your current proxy.

Summary #

  • Use the PHP file() to read the contents of a local or remote file into an array. Each line of the file will be an element of the array.
Did you find this tutorial useful?