Opening Files With PHP
Knowing how to open a file in php using the
fopen() function is basic stuff but is also quite useful. It can be applied to all sorts of different scripts like making a hit counter, logging visitor or download data perhaps, reading a random line from a file etc.
The basic format for using fopen() is
fopen('filename', 'mode') This is only the very basic syntax, there's more you can include inside the fopen() function depending on exactly what you're looking to do, but this is the minimum that you need to open any file.
The filename is quite obvious - the file that you want to open e.g
fopen('myfile.txt', 'mode') or you may want to set the file as a variable and use something like:
$file = 'myfile.txt';
The "mode" really depends what you want to do with the file when it's open (read, write etc) using the following
- r Opens the file for reading only and points to the beginning of the file.
- r+ Opens the file for reading and writing and points to the beginning of the file.
- w Opens the file for writing only and points to the beginnig of the file.
- w+ Opens the file for reading and writing and points to the beginning of the file.
- a Opens the file for reading only and points to the end of the file.
- a+ Opens the file for reading and writing and points to the end of the file.
If the file doesn't exist when using 'w', 'w+', 'a' or 'a+' it will attempt to be created.
Now if your file didn't open for some reason, you're going to want to know, so we'd use something like this to tell us.
$file = "myfile.txt";
fopen ($file, 'r') or die("cannot open $file\n");
We can also use some basic error checking to see if the permissions on the file we're trying to open are correct, e.g if you want to open a file to write to, well obviously it has to be writable.
$file = 'myfile.txt';
fopen ($file, 'w');
else echo("$file is not writable\n");
So if the file 'myfile.txt' is writable it'll be opened otherwise we'll get the message "myfile.txt is not writable"
Once again this is only the very basics of this function, but i hope it helps, if you want some more information on the above try The PHP Manual and you'll find a more detailed explination of fopen() is_readable() is_writable() and more related functions.