file_get_contents() reads a file as a string variable so it works well for removing multi-line javascript. There are other functions that read a file line by line into an array. This can be useful for a flat file (text based database). One such function is fopen().
fopen() accepts requires two arguments, a file name and a mode. (It also has some optional arguments that I will not cover.) The file name can be a simple file name, (name.txt) a file path or a full URL Mode tells if you are opening the file for reading, writing or appending. You can open an external file for reading but you cannot write or append to an external file. To read or append to your own file, it must have the proper permissions. For fopen() to create a new file, the directory must have the proper permissions. fopen() returns an argument that can be used in some other functions that is called a file resource or file handle.
| mode | Description |
|---|---|
| r | Read only Open for reading only. |
| r+ | Reading and Writing Open for reading and writing. If file does not exist, returns an warning message |
| w | Write only. Open for writing only. If file exists, PHP overwrites it If the file does not exist, attempt to create it. |
| w+ | Reading and Writing Open for reading and writing If file exists, PHP overwrites it If the file does not exist, attempt to create it. |
| a | Append Open for reading only. Appends data to the end of the file. If the file does not exist, attempt to create it. |
| a+ | Read and Append Open for reading writing. Appends data to the end of the file. If the file does not exist, attempt to create it. |
Unlike a PHP error message, an error message does not cause the script to abort. The script continues to run but any later functions that use that file resource will not work.
You can make the script abort if it can't open the file with a die statement:
$fr = fopen( "filename.txt", "r");
or die("Cannot open filename.txt");
The format for fopen is
$fr = fopen("filename", "mode")
After you have finished reading and/or writing to the file, you close it with the function fclose() with this format
fclose($fr);
|
|
|