The unlink
function in PHP deletes a file. However, it should not be confused with the unset
function in PHP, which is used to empty the file rather than delete it. The general syntax for the unlink
function is:
unlink(string $filename, resource $context = ?): bool
The unlink
function has one compulsory parameter and one optional parameter. filename
is the name of the file you wish to delete and is compulsory. The context
parameter is optional and sets the behavior of the stream.
The unlink
function returns true upon successfully deleting a file. However, if it fails, it will generate an E_Warning
.
The following example will help you understand the unlink
function better. As shown below, the file main.txt
is opened for writing and then closed using the fopen
, fwrite
, and fclose
functions. Then, we use the unlink
function and print its return value, demonstrating that the file has been successfully deleted.
<?php$file = fopen("main.txt","w");fwrite($file,"File testing");fclose($file);echo(unlink("main.txt"));?>
Free Resources