HTML TUTORIAL
» Introduction
» Elements
» HTML Tags
» Formatting
» Entities
» HTML Links
» Frames
» Tables
» Lists
» HTML Forms
» Images
» Layout
» Fonts
» Styles
» Head & Meta
» URL's
» Scripts
» Adding Music

PHP TUTORIAL
» Introduction
» Syntax
» Operators
» Conditionals
» Display the Date
» SSI - Includes
» Connecting to a Database
» PHP Forms
» Reading From a File

CSS TUTORIAL
» Introduction
» Syntax
» Inserting a Style Sheet
» CSS Backgrounds

DASHBOARD WIDGETS
» Hello World Widget

 
PARTNER LINKS

» Restaurant Menus
» Drew's News Room
» Stock Forums

READING FROM A FILE


This section describes file handling in PHP.


Opening a File

The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened in:

<html>
<body>
<?php
$f=fopen("welcome.txt","r");
?>
</body>
</html>

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

File Modes Description
r Read only. File pointer at the start of the file
r+ Read/Write. File pointer at the start of the file
w Write only. Truncates the file (overwriting it). If the file doesn't exist, fopen() will try to create the file
w+ Read/Write. Truncates the file (overwriting it). If the file doesn't exist, fopen() will try to create the file
a Append. File pointer at the end of the file. If the file doesn't exist, fopen() will try to create the file
a+ Read/Append. File pointer at the end of the file. If the file doesn't exist, fopen() will try to create the file
x Create and open for write only. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, try to create it
x+ Create and open for read/write. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, try to create it

Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

Example

The following example generates a message if the fopen() function is unable to open the specified file:

<html>

<body>
<?php
if (!($f=fopen("welcome.txt","r")))
exit("Unable to open file!"); 
?>
</body>
</html>


Closing a File

The fclose() function is used to close a file.

fclose($f);


Reading from a File

The feof() function is used to determine if the end of file is true.

Note: You cannot read from files opened in w, a, and x mode!

if (feof($f))
echo "End of file";


Reading a Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer has moved to the next character.

Example

The example below reads a file character by character, until the end of file is true:

<?php
if (!($f=fopen("welcome.txt","r"))) 
exit("Unable to open file.");
while (!feof($f)) 
{ 
$x=fgetc($f); 
echo $x;
}
fclose($f);
?>