Broad Network


PHP File Handling Basics

Basics of PHP Part 19

Forward: In this part of the series, I show you how to use PHP to open a text file, use it and close it.

By: Chrysanthus Date Published: 29 Jul 2012

Introduction

In this article I show you how to use PHP to open a text file, use it and close it. When you open a file, it comes to the computer memory from the disk. When you close it, it is saved back to disk. You can open a file, edit it and then close it to have it saved in the disk. If you want to create a new file, you still use the opening and closing process. When a file is opened and is in the memory, you do not see it on the computer screen. If you want it to appear on the computer screen, you have to write extra code for that. Word processors work in a similar way.

You need basic knowledge in HTML (or XHTML) and PHP in order to understand this article. You will try the code samples using your browser.

Note: If you cannot see the code or if you think anything is missing (broken link, image absent), just contact me at forchatrans@yahoo.com. That is, contact me for the slightest problem you have about what you are reading.

A Resource data Type
A resource is a reference to a memory location. The difference with this memory location and other memory locations is that you cannot access this one, arbitrarily. If the memory location has the content of a file, then you can only access it according to a particular mode (see below).  If you do not know the meaning of Reference, you can read the article I wrote, called PHP Reference, in this blog. To arrive at the article, just type, PHP Reference, and my name, Chrys in the Search box of this page and click Search. If you have the Google Search box, on the page, use it. However, you do not really need to understand Reference in order to understand this article.

Important Functions Used
There are two PHP predefined functions necessary to open and close a file: the fopen and fclose functions.

The fopen Function
In simple terms, the syntax of the fopen function is,

    resource fopen ( string $pathAndFilename , string $mode)

It returns a resource, which is a reference to a memory location or the Boolean value, false. There are two parameters. The first one is the path and file name in the disk. The second one is a string that gives the mode to access the memory location (the file in memory). The complete path and file name would be something like:

    "/path/to/filename.txt"

The first forward slash is for the highest-level directory. If the file you want to open is in the current working directory, you just have to type the file name. If the file is in a directory below the current working directory, then you have to type something like:

    "dirA/dirB/filename.txt"

where dirA is a directory just one level below the current working directory.

We shall look at the different string values for the different modes soon.

The return value, resource, of the fopen function is normally assigned to a variable as in the following example:

    $fileHandle = fopen("myfile.txt", "r");

You can give whatever name you want for the variable. The variable that receives the return value (reference) of the fopen function is called a File handle. You use this variable to do what you want to do with the memory location having the file content. There are predefined functions to use to edit files. You use the file handle like an ordinary variable in the predefined functions. The first argument in the fopen function above, is the name of a file that is in the current working directory. The second argument, "r" is an example (see below) of the mode that can be used to access the file content (memory location) in memory.

Note, if the fopen function does not succeed in reading a file it returns false. This is handy because some disks might have bad sectors and the opening process would fail. If your code detects false, you can inform the user that the file could not be read (through additional code).

The fclose Function
After opening a file and having done what you wanted to do with the file, you have to close it. You use the fclose function for that. When you close the file, the file content (edited) goes back to disk; the memory location that was used for the file is free, and can be used for any other thing in the program. Of course, the saved file can be a modified version of what you had before.

The syntax for the fclose function is:

    fclose ( resource $handle )

An example is

    fclose($myFHandle)

You use the variable to which the fopen function resource was assigned to, to close the file.

File Pointer in Memory
A file is made up of lines of text. While a file is in memory, it has a pointer. The pointer points to the next line that would be access. After the current line has been accessed, the pointer normally points to the next line. By default, the file pointer moves downward. The file pointer can also be interpreted as the file handle. You use a file pointer to access a file, line by line. You can also access a file character by character, but I will not address that.

The Mode Parameter
The mode parameter determines the kind of access you are allowed to make to the file in memory. Examples of such modes are: you can open a file to only read it and you can open a file to only write to it. There are many other options and this is determined by the mode parameter, which is a string of one or two characters. Here is what the PHP specification has about the possible mode arguments.

'r': Open for reading only; place the file pointer at the beginning of the file.  
'r+': Open for reading and writing; place the file pointer at the beginning of the file.  
'w': Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  
'w+': Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  
'a': Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  
'a+': Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  
'x': Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.
'x+': Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it.

End of File
The end of the file is the bottom end of the file. The feof function can be used to determine whether the pointer of the file in memory is at the end of the file in memory. The syntax is:

    bool feof ( resource $handle )

An example is:

    feof($myFHandle)

The return value is either true or false. True means end-of-file is reached. False means that pointer is not at the end-of-file. You can use this in an if-statement; some thing like,

    if (feof($myFHandle))
        //do this
    else
        //do that

When File cannot be opened
When a file cannot be opened, you can send out an error and terminate the current script. To output an error message and terminate the current script, you use the exit construct. Read and try the following script (make sure the file, afile.txt does not exist):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>

    <?php
        fopen('afile.txt', 'r') or exit('File does not exist.');
    ?>

</body>
</html>

You should have gotten the error message, 'File does not exist.' at the browser. The or you have before the exit function call above, is an operator. It works with the exit function. It means if the left operand returns false, the script should be exited. Remember, the fopen function will return either a resource or false.

We shall now go on to open a file for reading only; then open one for writing only; and then open one for reading and writing. However, before we do that, let us look at the predefined fgets function.

The fgets Function
The fgets function reads the line of the file in memory that the pointer is pointing to. In simple terms, the syntax is

    string fgets (resource $handle)

The return value is a string, which is the line of text read. An example of its use is:

    fgets ($myFHandle)

You can echo the return string to the browser.

Reading a File
Type the following content into your text editor as shown.

This is line one.
This is line two.
This is line three.

Save the file with the name myfile.txt in the current working directory. The current working directory is usually the directory having your PHP file. Make sure your operating system allows it to be read.

When the file is opened in memory, you can read each line into a variable or echo each line to the browser. To read a file from memory, line-by-line, from top to bottom, you use the while-loop, and the feof and fgets functions. Of course, to get the file into memory from disk in the first place, you have to use the fopen function. Finally, you free the memory location, close and save the file, using the fclose function. Read and try the following code (the php file should be different from the txt file, but all should be in the same directory):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>

    <?php
        $myHandle = fopen("myfile.txt", "r") or exit("Unable to open file!");

        while(!feof($myHandle))
         {
             echo fgets($myHandle), "<br />";
         }

        fclose($myHandle);

    ?>

</body>
</html>

For the fopen function, the mode argument is "r", which means that the file should be opened from the disk, for read only. While the end-of-file has not yet reached (notice the NOT operator in the while condition) the fgets function reads the next line in the file in memory. After each execution of the fgets function, the pointer points to the next line of the file in memory. The "<br />" in the code forces the next line to be displayed below the current line at the browser. After the last line is read, the pointer points to the end of file; the while-loop stops. After reading is complete, you have to free the memory location, so that the computer can use it for other things.

You can read each line into a variable or into array elements of an array. In the above case I have sent each line to the browser.

The fwrite Function
The fwrite function is used to write a string into the file content in memory at the position pointed to by the pointer. If the file is created (opened for the first time), then this will be at the beginning of the file (content in memory). In simple terms its syntax is:

    fwrite ( resource $handle , string $string)

An example of its use is given below.

Creating a new file and writing to it
In the following code, if you have a Unix based system, change \r\n to \n. If you have a Mackintosh based system, change it to \r. If you have a Windows based system allow it as it is. This indicates the end of line in a string. Read and try the code:

    <?php

        $aStr = "This first line.\r\nThe second line.\r\nThe third line.";

        $myHandle = fopen("hisfile.txt", "x");

        fwrite($myHandle, $aStr);

        fclose($myHandle);

    ?>

Now, go to the current working directory (where the php file is) and you should see a file created called, hisfile.txt. Use your operating system to open the file. You should see the content:

This first line.
The second line.
The third line.

Let me now explain the code. The first PHP line creates a string and assigns it to the variable, $aStr. The string has three lines. The next line in the code opens a file into memory using the fopen function. Because of the mode argument, "x", this file should not exist in disk and is created in memory to be saved at disk later. The third line, writes the string value into the file (memory location) in memory, using the fwrite function. The fclose function normally frees the memory location of a file in memory and saves the file to disk if it has undergone any changes. The last line in the above code saves the newly created file to disk.

Now, if you want the content to be what the user types, then you would have to use an HTML Form with a TEXT AREA element. After the user types into the text area and clicks the submit button, PHP code at the server will collect the content of the text area, assign it to a PHP string variable and then use the variable in the fwrite function.

Open a File for Reading and Writing
To open an existing file for reading and writing, you use either the 'r+' or 'a+' mode arguments for the fopen function. The 'r+' mode places the pointer at the beginning of the file in memory, while the 'a+' mode places the pointer at the end of the file in memory. If you use the 'r+' mode, whatever you add (write) will go into the beginning of the file. If you use the 'a+' mode, whatever you add (write) will go into the end of the file. In the example that follows, we shall use the 'a+' mode and the myfile.txt file, which should still be in your current working directory.

Read and try the following code, which should be self-explanatory (change the \r\n to \n or \r depending on your operating system):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
</head>
<body>

    <?php
        $myHandle = fopen("myfile.txt", "a+") or exit("Unable to open file!");

        while(!feof($myHandle))
         {
             echo fgets($myHandle), "<br />";
         }

        $appendedLine = "\r\nThis is line four.";
        fwrite($myHandle, $appendedLine);

        fclose($myHandle);

    ?>

</body>
</html>

All the file manipulation code occurs between the fopen and fclose functions in the above program. Now, use your operating system to open the file, myfile.txt and note the added line.

Note that to create a new file, you have to use the fopen function with the 'x' or 'x+' mode argument. You can also use some of the other mode strings, but 'x' and 'x+' are the most relevant.

Also note that it is possible to change the position of the pointer of the file content in memory, in order to access a particular line or character; however we shall not look at that in this article. There are also many other predefined functions to be used with an opened file; I have given you just the most common ones.

I hope from now onward, you will be able to handle the basics of files using PHP.

Chrys

Related Links

Major in Website Design
Web Development Course
HTML Course
CSS Course
ECMAScript Course
PHP Course

Comments

Become the Writer's Fan
Send the Writer a Message