Tag: Basics

Php File Handling Basics

PHP File Handling Basics

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


PHP Basics: Triple Equals

Curso Completo Domina la Salsa
Aprende Ahora El Baile Mas Latino Y Divertido, La Salsa, Con Nuestros Cursos 100% Practicos Y Entretenidos.
Curso Completo Domina la Salsa

The triple equal (===) compares not only values, but data types too. WEBSITE phpacademy.org FORUM http TWITTER twitter.com FACEBOOK www.facebook.com
Video Rating: 5 / 5

EbookCoversPro.com – Create eCovers instantly – 75% commissions
eBookCoversPro is a service allowing users to easily with point and click software to create eCovers and 3d eCovers. 75% commissions. Make sure you visit our landing page to check out our sales copy!
EbookCoversPro.com – Create eCovers instantly – 75% commissions
3-Click Article Poster
Software to post articles to blogs automatically, creating automatic product links. Context-sensitive hypertext links and footers can be created for any blog. Maximum “Search Engine Juice” with minimum effort, increase income from affiliate product sales
3-Click Article Poster


  • Copyright © 1996-2010 Programming tutorials for beginners,. All rights reserved.
    iDream theme by Templates Next | Powered by WordPress