Tutorialspoint.dev

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.

  1. filename : It is a mandatory parameter which specifies the filename of the file which has to be deleted.
  2. 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

  1. The unkink() function generates an E_WARNING level error on failure.
  2. The web server user must have write permissions to the directory for using the unlink() function.
  3. 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



This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter