PHP | unlink() function
The unlink() function in PHP is an inbuilt function which is used to delete a file. It is similar to the unlink() function found on Unix.
The filename of the file which has to be deleted is sent as a parameter and the function returns True on success and False on failure.
Syntax:
unlink(filename, context)
Parameters Used:
The unlink() function in PHP accepts two parameter.
- filename : It is a mandatory parameter which specifies the filename of the file which has to be deleted.
- context : It is an optional parameter which specifies the context of the file handle which can be used to modify the nature of the stream.
Return Value:
It returns True on success and False on failure.
Errors And Exception
- The unkink() function generates an E_WARNING level error on failure.
- The web server user must have write permissions to the directory for using the unlink() function.
- The unlink() function returns Boolean False but many times it happens that it returns a non-Boolean value which evaluates to False.
Examples:
Input : $file_pointer = "gfg.txt";
if (!unlink($file_pointer))
{
echo ("$file_pointer cannot be deleted due to an error");
}
else
{
echo ("$file_pointer has been deleted");
}
Output : 1
Input : $file_pointer = fopen('gfg.txt');
fwrite($file_pointer, 'A computer science portal for geeks!');
fclose($file_pointer);
unlink('gfg.txt');
Output : 1
Below programs illustrate the unlink() function.
Suppose there is a file named “gfg.txt”
Program 1
<?php // PHP program to delete a file named gfg.txt // using unlike() function $file_pointer = "gfg.txt"; // using unlink() function to delete a file if (!unlink($file_pointer)) { echo ("$file_pointer cannot be deleted due to an error"); } else { echo ("$file_pointer has been deleted"); } ?> |
Output:
1
<?php // PHP program to delete a file named gfg.txt // using unlike() function $file_pointer = fopen('gfg.txt'); // writing on a file named gfg.txt fwrite($file_pointer, 'A computer science portal for geeks!'); fclose($file_pointer); // using unlink() function to delete a file unlink('gfg.txt'); ?> |
Output:
1
Reference:
http://php.net/manual/en/function.unlink.php
Recommended Posts:
- PHP | abs( ) Function
- p5.js | box() Function
- PHP Ds\Set get() Function
- PHP Ds\Set sum() Function
- p5.js | hue() function
- PHP | each() Function
- PHP | sin( ) Function
- PHP | tan( ) Function
- PHP | pos() Function
- PHP | end() Function
- p5.js | nf() Function
- p5.js | nfc() function
- p5.js | nfp() Function
- p5.js | nfs() Function
- p5.js | min() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



