Page 191 - Open Soource Technologies 304.indd
P. 191
Open Source Technologies
Notes Here is a breakdown of the modes:
w: This is the write mode, used to open a file for writing, Whenever this is used the file
associated with the command will be recreated. w+ enables read/write mode.
r: This mode is used to open a file for reading. r+ enables read/write mode.
a: This is the append mode, your content will be added to the file therefore keeping any
data already in the file. Change to a+ to enable read/write mode.
11.4 Delete File
Deleting a file using PHP is done by using the unlink function. Such a simple function with so
much power! You need to use extreme caution when using the unlink function, as you don’t
want to accidentally delete a crucial file that is needed elsewhere for other functions. You can
not delete a file that is already open using the fopen() function, as it is already being used.
However, once you close a file you have the ability to delete it.
If the file is already opened, we need to use the fclose function to close the file. Remember how
it is done:
fclose($file);
This is assuming the file that is opened is assigned the variable $file previously. (See fopen())
Now that the file has been closed, you have the ability to delete the file:
$file = “myfile.txt”;
unlink($file);
First, you define which file you wish to delete. In this case, the file “myfile.txt” is defined using
the variable “$file”. Once you have defined the file, you then delete it using the unlink function.
After executing the unlink function, the file will then be removed.
11.5 Opening a File for Reading
The fopen() function is used to open files in PHP. The first parameter of this function contains
the name of the file to be opened and the second parameter specifies in which mode the file
should be opened:
<html>
<body>
<?php
$file=fopen(“welcome.txt”,”r”);
?>
</body>
</html>
186 LOVELY PROFESSIONAL UNIVERSITY