PHP files, how to read and write to files ?

In this lesson we will talk about using files in php: Reading, Writing and overwriting files.

To open a file
The first thing, before reading or writing to a file, we need to open it, to be ready.

To open a new file in php, use this script:
$filename = "myfile.txt";
$handle = fopen($filename, "r");



This is very easy ! Yes ?
$filenam is just the name and path of the file you want to open to eighter read or write, it can be "something.txt" if it's in the same folder than the php page, or like :"folder1/something.txt" if its in another folder.
In the second line, fopen($filename, "r") , the "r" means that we will read the file, all possible values are:
"r" : Only read a file
"r+" : read and write, start from the begenning of the file.
"a" : write only, write to the end of the file.
"a+" : write and read, start from the end of the file.
"w" : Delete the content of the file, and write over it.
"w+" : Delete the content of the file, then you can read or write to it.

To read a file:

Now, to read a file and copy the content to a string:
$contents = fread($handle, filesize($filename));


Now in the variable $contents you have all the text in the source file.
The script should be:
$filename = "myfile.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));


you can then use echo function to write it to the html page, or you can split it by a delimiter ( we will se that soon).

To write to a file:

As we said before, there are many ways to write to a file:
To write to the beginning of the file, use the "r+" in the fopen() function.
To write to the end of the file, use the "a" in the fopen() function.
To overwrite the file, if you want to replace the current content of the file, then use the "w" in the fopen() function.

Then :
$filename = "myfile.txt";
$handle = fopen($filename, "a");
fwrite($handle, 'some text to add to the file');

In this case you will put the scring to the end of the file

In case you want to put a string to the begenning to the file, just use: "r+", just like that:
$filename = "myfile.txt";
$handle = fopen($filename, "a");
fwrite($handle, 'some text to the beginning oh the file');


Or, if you want to overwrite the file with php, you can use "w".
$filename = "myfile.txt";
$handle = fopen($filename, "w");
fwrite($handle, 'new content for the file');


This is easy, don't think ?

It may be very helpful to check if the file can be read or wrote, you can use this script:
$handle = fopen($filename, "w") or die("can't open the file");




The next lessons will be about reading external files. Soon :)

0 comments: