Use PHP Open and Read a File or URL

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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>