To open a file we need this code:
Code:
<?php
if (!($f=fopen("file.txt","r+")))
exit("File Opening Error");
?> Explination: fopen() - this opens the file. The first section (file.txt) is the file name, the second (r+) defines how the file shall be opened, we will come back to this.
exit() - This displays an error message if the file fails to open.
Now, you saw the
r+ mode? I'll explain all of these and what they are.
r - Read Only. File pointer at the start of the file.
r+ - Read and Write. File pointer at the start of the file.
w - Write Only. Overwrites the file...if the file doesn't exist then fopen() will attempt to create it.
w+ - Read and Write. Overwrites the file...if the file doesn't exist then fopen() will attempt to create it.
a - Append. File pointer at the end of the file. if the file doesn't exist then fopen() will attempt to create it.
a+ - Read and Append. File pointer at the end of the file. if the file doesn't exist then fopen() will attempt to create it.
x - Create and Open for Write Only. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, it will attempt to create it.
x+ - Create and open for Read and Write. File pointer at the beginning of the file. If the file already exists, the fopen() call will fail and generate an error. If the file does not exist, it will attempt to create it.
If
fopen() is unable to open the file, it will return as false (0).
---
Now to close the file...
fclose($f); - This closes the current open file.