Open In App

PHP | unlink() Function

The unlink() function is an inbuilt function in PHP which is used to delete files. It is similar to UNIX unlink() function. The $filename is sent as a parameter that needs to be deleted and the function returns True on success and false on failure.

Syntax:



unlink( $filename, $context )

Parameters: This function accepts two parameters as mentioned above and described below: 

Return Value: It returns True on success and False on failure.



Errors And Exception:

Below programs illustrate the unlink() function in PHP:

Suppose there is a file named as “gfg.txt”
Program 1:




<?php
// PHP program to delete a file named gfg.txt
// using unlink() function
 
$file_pointer = "gfg.txt";
 
// Use 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: 

gfg.txt has been deleted

Program 2:




<?php
// PHP program to delete a file named gfg.txt
// using unlink() function
 
$file_pointer = fopen('gfg.txt', 'w+');
   
// writing on a file named gfg.txt
fwrite($file_pointer, 'A computer science portal for geeks!');
fclose($file_pointer);  
 
// Use 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: 

Warning: unlink() expects parameter 1 to be a valid path, resource
given in C:\xampp\htdocs\server.php on line 12
Resource id #3 cannot be deleted due to an error

Reference: http://php.net/manual/en/function.unlink.php
 


Article Tags :