PHP Unlink Function With Example Program

unlink( filename, context )

This function takes two parameters, which have already been mentioned and are explained below:

  • filename: It is a required parameter that tells the program what file it needs to delete.
  • context: It is an optional parameter that gives the file handle’s context and can be used to change how the stream works.

If the file is deleted successfully, it returns True. If not, it returns False.

Additionally, according to PHP documentation, unlink deletes the filename.

Similar to the Unix C unlink() function. An E_WARNING level error will be generated on failure.

VersionDescription
7.3.0On Windows, you can now unlink() files that are being used by a handle, which used to be impossible. But the unlinked file can’t be made again until all of the handles to it have been closed.

Example 1:

Delete an Existing File

If the sample.txt file already exists, use the following script to delete it from the PHP file: The script uses the file_exists() function to check if the file already exists or not.

If the file is already in the current location, the unlink() function will delete it.

An error message will be shown if the file is not in its current location.

<?php
    $filename = "sample.txt";

    if(file_exists($filename)) {
        if (!unlink($filename)) {
            echo ("<br />Error occurs while deleting the $filename file.");
           }
        else {
            echo ("</br>The <b>$filename</b> file has been deleted.");
           }
    }else
        echo "<br />The <b>$filename</b> file does not exist.";
?>

Output:

If the file was at the current location, the following output would result from executing the previous code:

The samle.txt file has been deleted.

Example 2:

Delete the File After Creation

Create a PHP file with the following script to remove the sample.txt file after generating the file.

The script uses the file_exists() function to determine whether the file has been created.

If the file already exists at the current location, the unlink() function will remove it.

If the file is not present, an error message will be presented.

<?php
    $filename = "sample.txt";

    $fh = fopen($filename, 'w+');

    fwrite($fh, 'Welcome to itsourcecode.');
    fclose($fh);

    if(file_exists($filename)) {
        echo "<br />The <b>$filename</b> file exists.";
 
        if(!unlink($filename)) {
            echo ("<br />Error occurs while deleting the $filename file.");
        }else {
            echo ("<br />The <b>$filename</b> file has been deleted.");
        }
    }else
        echo "<br />The <b>$filename</b> file does not exist.";
?>

Output:

If the file was created and removed correctly, the following output would display after executing the prior script:

The sample.txt file exists.
The sample.txt file has been deleted.

Example 3:

Delete All Files of the Particular Extension

Create a PHP file with the following script to delete all text files. Before removing each text file, its name and size will be printed.

<?php
    foreach (glob("*.txt") as $filename) {
        echo "<br />The filename is $filename";
        echo "<br />The size of the file is ".filesize($filename)." bytes.";

        if (!unlink($filename))
            echo ("<br />Error occurs while deleting the $filename file.");
        else
            echo ("<br />The <b>$filename</b> file has been deleted.");
    }
?>

Output:

Following the execution of the preceding script, similar results will be generated.

The result below indicates that three text files were deleted from the current directory.

The filename is Sample.txt
The size of the file is 22 bytes.
The Sample.txt file has been deleted.
The filename is Notes.txt
The size of the file is 47 bytes.
The Notes.txt file has been deleted.
The filename is document1.txt
The size of the file is 5 bytes.
The document1.txt file has been deleted.

Example 4

Delete All Files From the Particular Directory

Create a PHP file with the following script to remove all files from the “images/portrait_id” directory.

Similar to the preceding example, the name and size of each file will be displayed prior to removing it.

The string "*.*" is used in the script to represent all file types regardless of their extension.

<?php
    $dir_path = "images/portrait_id";

    foreach (glob($dir_path."/*.*") as $filename) {
        echo "<br />The filename is <b>$filename</b>";
        echo "<br />The size of the file is <b>".filesize($filename)."</b> bytes.";
        if (!unlink($filename))
            echo ("<br />Error occurs while deleting the <b>$filename</b> file.");
        else
            echo ("<br />The <b>$filename</b> file has been deleted.");
    }
?>

Output:

Following the execution of the preceding script, similar results will be generated.

The output indicates that a single file was deleted from the current directory.

The filename is images/portrait_id/johndoe.jpg
The size of the file is 32562 bytes.
The images/portrait_id/johndoe.jpg file has been deleted.

Example 5

Delete All Files and Folders From the Directory

A directory may include multiple sub-directories, folders, and files. All files and folders must be deleted prior to removing a directory.

Create a PHP file with the following script to remove files and directories from a directory.

The script uses the user-defined method removeDir() to remove all files and folders from the “images” directory and make it empty.

When the transient directory gets empty, it will be deleted.

<?php
$dir_path = "/images";
function removeDir($path) {
    $files = glob($path . '/*');
    foreach ($files as $file) {
        is_dir($file) ? removeDir($file) : unlink($file);
 
        rmdir($path);
        return1;
    }
    if(removeDir($dir_path))
        echo "All files and folders including $dir_path directory has been deleted.";
    else
        echo "Error occurred at the time of deletion.";
}
?>

Output:

If the temp directory exists at the current location, the following output will be generated when the above script is executed.

All files and folders including images directory has been deleted.

Frequently Ask Questions (FAQs)

The unlink() function must eliminate a file’s link.

If the path specifies a symbolic link, unlink() will destroy that symbolic link without affecting any file or directory indicated by the symbolic link’s contents.

PHP’s built-in unset() method is mostly used to unset a variable.

The operation of this variable is contingent upon multiple factors. Suppose that a specific function is called within a user-defined function.

In this situation, it will remove the value connected with the variable and leave the value initiated from the outside, meaning the function can only remove local variables.

Still, $ GLOBAL array must be used to unset global targets in order to complete the process.

Summary

In summary, we have learned how to use the PHP unlink function in different situations.

You should be able to use the information here to create your own advanced applications.

Lastly, if you want to learn more about unlink in PHP, please leave a comment below. We’ll be happy to hear it!

Leave a Comment