Online: 103   Members: 4,232

Working with files in PHP

Here we will discuss the common filesystem functions available to you. First of all, in order to do anything with a file, we must first open it. To do so we will use the following line:

$filehandle = fopen("/path/to/file", "w");

The ''w'' is an argument that tells the system what you plan to do with the script. Here are the possible choices:

'r' = Open the file and place the file pointer at the beginning of the file. You will receive an error if the file does not exist.
'r+' = Open file for reading and writing, otherwise same as above.
'w' = Write to a file. If the file does not exist, it will attempt to create it. If it does exist it truncates the file and you overwrite it.
'w+' = Open the file for reading and writing. Otherwise same as above.
'a' = Open the file for writing. If the file does not exist, it will attempt to create it. If it does exist, it will add to the end (not overwrite).
'a+' = Open file for reading and writing. otherwise same as above.

Now that we have successfully created a variable to open the file, lets go ahead and read it.

$contents = fread($filehandle, filesize("/path/to/file"));

The fread function requires both the fopen statement and the size of the file to read. Luckily, we have the filesize() function to find that for us. Now lets attempt to add some new content to the file.

fwrite($filehandle, "This is some new content blah blah");

Once again, the fwrite function also requires our fopen $filehandle to work correctly. Lastly, make sure you close the file to prevent corruption and/or data loss.

fclose($filehandle);

That''s it!

Related Tutorials

Useful Resources