Login |  Register 
I thought I knew all about PHP until I found this website!
Jen
 

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.
 */

Comments to date: 9. Page 1 of 1. Average Rating:
Teddy   8:49am on Saturday, March 25th, 2017 
Gud.. I need more syntax like this..
ps   3:36am on Friday, August 19th, 2016 
fedfd
Ranveer Yadav   5:21am on Wednesday, September 16th, 2015 
Hello
johnboss   3:13pm on Monday, June 15th, 2015 
Liked the tutes
sonu   11:56am on Tuesday, April 14th, 2015 
whats that
SAMPLE   3:26am on Monday, February 23rd, 2015 
VERY GOOD
Genius   1:28am on Monday, October 6th, 2014 
very very poor
erew   1:47am on Friday, August 31st, 2012 
erwqr
Calvin   4:30pm on Monday, July 2nd, 2012 
I'm ipmerssed you should think of something like that

security image
Written by Dominic Skinner
Last Updated: 2011-10-25 16:00:38