How to Read a File in PHP
Reading the contents of a file is an important part of dynamic Web scripting as well as command-line scripting. PHP allows you to read a file and print it to a screen or to another file or database. When used within a larger script, it allows you to have different files printed to a Web page based on particular user variables. It can also be useful for command-line text processing in both Windows and Unix/Linux environments.
Instructions
-
-
1
Open a blank text file in any text editor such as Windows Notepad or GEdit and Kate in Linux.
-
2
Begin typing the PHP script in the blank text file:
<?php
-
-
3
Open the file with the fopen function:
$file = fopen("example.txt", 'r');
The 'r' parameter tells the fopen function to open the file for reading only.
-
4
Begin the while statement that will loop until the end of the file:
while (!feof($file)) {
-
5
Read the file with the fgets function and place it in the variable $data:
$data = fgets($file);
The fgets function will read the file line-by-line unless a byte limit is provided.
-
6
Print each line to the screen and close the while loop:
echo $data;}
-
7
Close the file:
fclose($file);
-
8
End the PHP script:
?>
The entire script will look like:
<?php
$file = fopen("example.txt", 'r');
while (!feof($file)) {
$data = fgets($file);
echo $data;}
fclose($file);
?> -
9
Open the command prompt in Windows or a terminal window in Linux/Unix. In Windows, select "Start" > "All Programs" > "Accessories" > "Command Prompt." In Linux or Unix, open the terminal window under the "System Tools" or "Utilities" submenu in your operating system's main "Applications" menu.
-
10
Run the script from the command line in the directory with the text file "example.txt":
php test.php
-
1
Tips & Warnings
If the PHP script is stored in a different directory than where your text file is located, you must specify the exact path to the text file in the fopen function.