Files
You often have to save or read a resource in web development an easy way to do this is to read and write from
files.
Reading a file
We will cover the simplest way to read a file using the
file_get_contents function.
//Simply give it the relative path of the file to read
$contents = file_get_contents('text.txt');
echo $contents;
The file reads the text.txt file and outputs it into a string. This is the simplest way to read a file you can also limit the amount you read so
$contents = file_get_contents('text.txt', false, null, 0, 1024);
This reads the first 1024 bytes or the first Kilobyte.
You can also use the
file_get_contents function to read webpages so:
//Simply give it the url of the web page to read
$contents = file_get_contents('http://www.google.com');
Will read Googles main web page!
Writing to a file
The simplest way to write to a file is to use the
file_put_contents function.
//Simply give it the file to write to and the data
$data = 'hi there';
file_put_contents('text.txt',$data);
This returns false if there was an error or a number of bytes that was written if it was successfull so we can further improve this
code with some logic like:
//Simply give it the file to write to and the data
$data = 'hi there';
if (!file_put_contents('text.txt',$data))
{
echo "There was an error writing your data to the text.txt file";
}
This function will actually create a non-existing file by default and as well as overwriting existing files.
So it might be a good idea to only let the file append by setting the file append flag.
//Simply give it the file to write to and the data
$data = 'hi there';
if (!file_put_contents('text.txt',$data, FILE_APPEND))
{
echo "There was an error writing your data to the text.txt file";
}
Good practice
Usually when dealing with files it is good to see if the file exists before doing something with it, this makes your code
more reliable. To do this the
file_exists function can be used.
//Simply give it the file name to check that exists
if (!file_exists('text.txt'))
{
echo "Your file doesn't exist!";
return;
}
/*
* Rest of the file accessing code.
*/
No comments have been provided.
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38