PHP is an easy-to-learn programming. PHP is a very poweful program to create dynamic and interactive web pages. In fact, many dynamic websites on the Intenet are made up with PHP. And the most important thing is that PHP is free, that’s explain why it is so widely use on the Internet. The other main reason why PHP is so popular may be that it can easily be interacted with MySQL database.

Our PHP tutorials are both interesting and easy to follow. All PHP tutorials will be illustrated with examples, rather than just explaining the syntax and structure.

I sometimes use PHP to open and read a file. This is very simple and easy but very useful. Let’s discuss briefly this topic today.

Use PHP Open and Read a File or URL

I am now going to open a text file (urls.txt) and read the contents. For simplicity, there is only one line of urls.txt. Here’s the contents of urls.txt:

To open and read a file with PHP involves two steps – open a file and then read the file.

PHP fopen() Function

The PHP fopen() function can opens a file. The file already exist, so use “r” for read only. For example:

$fp = fopen($file, “r”);

PHP fgets() Function

The PHP fgets() function returns a line from the opened file. We need to tell the number of bytes of the opened file to read. The default number of bytes is 1024 bytes. For example:

$data = fgets($fp, 1024);

Here’s the example of open and read a file or URL with PHP:

    <title>PHP Open and Read File</title>


<h2>Use PHP Open and Read a File</h2>


// File to open
$file = "urls.txt";

// Open the file
$fp = fopen($file, "r");

// Read and get a line from the opened file
$data = fgets($fp, 1024);

echo "The data are: " . $data;



PHP Example File:

Click here to download.

This post discuss how to use PHP to open and read a file.