Sunday, March 21, 2010

PHP File Handling

----------------------------------------------------------------------------------------------------------------------------------
The fopen() function is used to open files 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:


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


*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:



Closing a File

The fclose() function is used to close an open file:



Check End-of-file (EOF)

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

The feof() function is useful for looping through data of unknown length.

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

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


Reading a File Line by Line

The fgets() function is used to read a single line from a file.

*NOTE:
After a call to this function the file pointer has moved to the next line. For instances:



Reading a File Character by Character

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

*NOTE:
After a call to this function the file pointer moves to the next character. For instances:

0 comments:

Post a Comment