|
|
| MAKE/WRITE/DELETE TEXTFILES IN PHP |
|
When you want to store some data, either how many viewers your page have registered,
or you want to make a simple guestbook, you have to store the data. Textfiles is
a rather easy way to do this. In this tutorial I will show how to make, write to and
delete a textfile. I will not make a live example in this tutorial due to security. But you can
cut and paste the code into your own code.
|
Make And Write To A File
|
|
You use the same methods for writing to a file, and making a new. If the file
already exists, you will repleace the content with the new -> write new data to it.
|
//the filename
$filename = "myfirstfile.php";
//make the file, if it exists it will overwrite it
$fp = fopen($filename,"w") or die ("Error Opening File");
//set the content into the file
fputs($fp,$content);
//close the file
fclose($fp;
|
|
If you want to replace part of the text file, I recommend you use xml files
or a database to store your data. I have however made a wrapper class where
you can manipulate the textfile. You can download the class and read more about it
here.
|
Delete A File
|
|
When we will get a file on the server you are working you use
the @ sign, as below. We delete a file with the code below.
|
$filename = "filetodelete.txt";
$delete = @unlink($filename);
if (@file_exists($filename))
{
$filesys = eregi_replace("/","\\",$filename);
$delete = @system("del $filesys");
if (@file_exists($filename))
{
$delete = @chmod ($filename, 0775);
$delete = @unlink($filename);
$delete = @system("del $filesys");
}
}
|
|
Category
|
Programming with PHP
|
|
Author
|
Tommy Johannessen
|
|
|
|