PHP File IO with Example Program

In this tutorial, we will go through PHP File IO, and of course, there will be an example program included.

Before we begin, if you missed any of our prior lessons, you can review the topics in our PHP Tutorial for Beginners.

PHP Open File – fopen()

The fopen() function is a better way to open files. This function is better than the readfile() function because it gives you more options.

During the lessons, we will use the text file “phptutorial.txt“:

AJAXAsynchronous JavaScript and XML
CSSCascading Style Sheets
HTMLHyper Text Markup Language
PHPPHP Hypertext Preprocessor
SQLStructured Query Language
SVGScalable Vector Graphics
XMLeXtensible Markup Language
File Upload in PHP with Source Code...
File Upload in PHP with Source Code 2021 | PHP Tutorial with Source Code

The first parameter of the fopen() function is the name of the file to be opened, and the second parameter tells fopen() how to open the file. If the fopen() function is unable to open the specified file, the following example will also print a message:

<?php
$file_txt = fopen("phptutorial.txt", "r") or die("Can't open file. Please try again!");
echo fread($file_txt,filesize("phptutorial.txt"));
fclose($file_txt);
?>

We’ll talk about the fread() and fclose() functions below.

The file may be opened in one of the following modes:

ModesDescription
rOpen a file as a read-only file. The file pointer starts at the file’s beginning.
wOpen a file as a write-only file. Deletes the file’s contents or, if the file does not exist, creates it. The file pointer begins at the file’s beginning.
aOpen a file as a write-only file. Existing data in the file is maintained. The file pointer starts at the file’s end. Creates a file if it does not already exist.
xCreates a new file as a write-only. If the file already exists, returns FALSE with an error.
r+Open a file as a read/write. The file pointer starts at the file’s beginning.
w+Open a file as a read/write file. Deletes the file’s contents or, if the file does not exist, creates it. The file pointer begins at the file’s beginning.
a+Open a file as a read/write file. Existing data in the file is maintained. The file pointer starts at the file’s end. Creates a file if it does not already exist.
x+Creates a new file as a read/write. If the file already exists, returns FALSE with an error.

PHP Read File – fread()

The fread() function reads from a file that is open.

The first parameter to fread() indicates the file to read from, while the second defines the maximum number of bytes to read.

The PHP code below reads the entire “phptutorial.txt” file:

<?php
fread($file_txt,filesize("phptutorial.txt"));
?>

PHP Close File – fclose()

A file is closed using the fclose() method.

It is best practice for programmers to close all files when they are no longer needed. You do not want an open file running around on your server, using resources!

The function fclose() requires the filename (or a variable containing the filename) to be closed:

<?php
$file_txt = fopen("phptutorial.txt", "r");
// code here
fclose($file_txt );
?>

PHP Read Single Line – fgets()

In the fgets() function, we can read one line from a file.

The “phptutorial.txt” file’s first line is shown in the example below:

<?php
$file_txt = fopen("phptutorial.txt", "r") or die("Can't to open file!");
echo fgets($file_txt);
fclose($file_txt);
?>

Note: When the fgets() function is called, the file pointer moves to the next line.

PHP Check End-Of-File – feof()

The feof() function checks if the file has reached the “end-of-file” (EOF).

The feof() function is handy for iterating through data with an uncertain length.

The following example reads the “phptutorial.txt” file line by line until it reaches the end of the file:

<?php
$file_txt = fopen("phptutorial.txt", "r") or die("Can't open file!");

// Output a single line till the file's end
while(!feof($file_txt)) {
  echo fgets($file_txt) . "<br>";
}

fclose($file_txt);
?>

PHP Read Single Character – fgetc()

The fgetc() function reads a single character from a file.

The following example reads the “phptutorial.txt” file character by character until it reaches the end of the file:

<?php
$file_txt = fopen("phptutorial.txt", "r") or die("Can't open file!");

// Output one character until end-of-file
while(!feof($file_txt)) {
  echo fgetc($file_txt);
}

fclose($file_txt);
?>

After calling the fgetc() method, the file pointer advances to the following character.

Frequently Ask Question

How do I read a PHP file?

To read a PHP file, first we are going to open the file by using the function called fopen(). Then, to get the file length, we’re going to use the filesize() function.

Then, to read the PHP file, we are going to use the fread() function. Finally, don’t forget to close the file, so to close it we are going to use the fclose() function.

Additional information about fread() function from PHP Official Documentation, fread() reads up to length bytes from the file pointer referenced by stream.

What is the PHP file?

A PHP file is often a plain-text file containing PHP code. Since PHP is a server-side (back-end) scripting language, the PHP file contains code that is executed on the server.

The PHP engine on the web server turns all PHP code into HTML. This means that when the web page is sent to the client side to be displayed in the user’s browser, it only has HTML code. 

What is PHP file handler?

The PHP File System enables us to create files, read them line by line, character by character, write them, append them, delete them, and close them.

Where can I open a PHP file?

A PHP file is a simple text file, therefore it can be opened with any text editor, such as Atom, Notepad, or Sublime Text.

Sublime Text should be enough for beginners, as they will only execute little code bits. However, as you go to more advanced PHP programming, you should consider upgrading to advanced editors and integrated development environments (IDEs) that provide syntax highlighting syntax auto-completion, and extensive search capabilities.

How do PHP files work?

The PHP executes system actions, including the creation, opening, reading, and closing of system files. It is capable of managing formats, thus it can gather data from databases, store data in a file, transmit data via email, and return data to the user. PHP also allows you to add, delete, and modify database items.

Summary

In summary, we have studied the different filesystem functions in PHP. We also included examples to help you better comprehend each function.

Lastly, if you want to learn more about PHP File IO, please leave a comment below. We’ll be happy to hear it!

Leave a Comment