|The fopen( ) and fclose( ) functions are two of many PHP filesystem functions and are used together, along with their modes, to open and close an existing file that is part of your website. In certain cases, the fopen( ) function may also be used to generate a new file. For example, if you want a database driven online product catalog but you do not have MySQLR or another database system available. You can use a text file database. In this case, you will need to open one or more files, collect the data from the files and display the catalog information. Let’s take a look at the fopen( ) and fclose( ) code. |
The mode, placed between parentheses, indicates to the program how to setup the information in the file. In our example, the mode is set to “r” which indicates the file is to be read. The mode also tells the program where to put the pointer within the file. The pointer “points to” the location where you wish to begin reading the contents of the file. To read the entire file, the pointer will be placed at the beginning of the file. The chart below contains descriptions of the most common modes.
As you might have noticed, it is very important to use the correct mode with the fopen( ) function or you might inadvertently place the pointer at the beginning of your file and delete all the data from your existing file. Also, some modes will create a new file with the fopen( ) function, if a file of that name does not already exist.