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. :
$filename = "text.txt"; $f = fopen($filename, 'r');
The above code assigns the file name of "text.txt" to a variable called $filename. Then it uses the fopen 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:
- Create a file handler.
- Use the file handler to open up an input stream from a file.
- Write Data to the file handler.
- Close the file handler.
Here is an example of writing two lines of text to a file:
$filename = "file.txt"; $f = fopen($filename, 'w'); fputs($f, "Bonjour Madam.\n"); fputs($f, "Bonjour Monseur.\n"); fclose($f);
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.
$filename = "text.txt"; $f = fopen($filename, 'r'); $line = fgets($f, 1024); print $line; print $total_contents; fclose($f);
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 :
$total_contents = fread($f, filesize($filename));