PHP and MySQL Programming/File Handling

As with most programming languages, file handling is very important for storing and retrieving a wide variety of data.

Opening and Closing Files
To open a file, we use the fopen function. This function takes in two parameters. Firstly, a String containing the name of the file, and secondly, the mode with which to open the file with. It returns a filehandler. e.g.:

The above code assigns the file name of "text.txt" to a variable called $filename. Then it uses the  function to open up "text.txt" with 'r' mode (meaning "read mode") and returns a filehandler to $f.

To close a file, we simply call the fclose function, and pass it the filehandler. e.g.:

Including a File
It is very easy, in PHP, to include code (be it PHP or HTML) from one file into another. This is achieved by means of the include function.

In the above example, the PHP code will look within the current directory of the PHP file calling the include function, it will then open the objects.php file, and include its content at of that file at the position of the include function.

Writing to a File
The procedure for writing to a file is:
 * 1) Create a file handler.
 * 2) Use the file handler to open up an input stream from a file.
 * 3) Write Data to the file handler.
 * 4) Close the file handler.

Here is an example of writing two lines of text to a file:

fputs is used to write data to the file. It takes 2 variables, firstly, the file handler, and secondly, a String to write to the file handler.

Reading from a File
Reading from a file goes along much the same format as writing to one. The function used to read from a file is fgets function. Which takes in two variables. Firstly, the filehandler from which to read, and secondly, the amount of data to retrieve.

The above code opens up a file, reads the first line of the file, and then displays it. If we wanted to rather read the entire contents of the file into a variable, we could replace the $line=fgets line with: