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!

Common use cases for PHP Unlink Function

  • Input validation. Check that expected data is present before using it in business logic.
  • Conditional rendering. Display forms differently for logged-in vs guest users.
  • Guard clauses. Early return at the top of a function if required data is missing.
  • Session and cookie checks. Verify a user’s authentication state before serving protected content.
  • Configuration existence. Confirm a config value is set before falling back to a default.

Working code example

<?php
function greet($name = null) {
    if (!isset($name) || $name === "") {
        return "Hello, guest!";
    }
    return "Hello, " . htmlspecialchars($name) . "!";
}

echo greet("Alice"); // Hello, Alice!
echo greet();        // Hello, guest!
echo greet("");      // Hello, guest!
?>

Common pitfalls

  • isset() vs empty(). isset() checks if variable exists and is not null. empty() also returns true for 0, “”, “0”, empty arrays.
  • Undefined index warnings. Accessing $_POST[“key”] without isset() first triggers E_WARNING in PHP 7 and E_DEPRECATED in PHP 8.
  • Falsey values. null, false, 0, “”, “0”, empty array all evaluate to false. Use === for strict comparison when needed.
  • Function name conflicts. If your function name matches a PHP built-in, PHP throws a fatal error. Prefix with your namespace.

Best practices

  • Use type declarations. function greet(?string $name = null): string catches wrong types at compile time.
  • Early return over deep nesting. Guard clauses at the top improve readability.
  • Prefer null-safe operator (PHP 8+). $user?->getName() cleaner than isset() chains.
  • Namespace your functions. Group related functions in a namespace to avoid pollution.

Frequently Asked Questions

What PHP version does this tutorial target?
This tutorial is written for PHP 8.0 or higher. Modern features (arrow functions, named arguments, match expressions, enums, nullsafe operator) work best in PHP 8.1+. For legacy PHP 7.x, most examples still run but with fallback syntax.
Do I need XAMPP to run PHP code examples?
For beginners, XAMPP (Apache + PHP + MySQL) is the easiest setup on Windows. On Mac, use MAMP or Homebrew php. On Linux, install php-cli via apt or yum. For quick one-off tests, use an online PHP sandbox like PHP Sandbox or 3v4l.org.
How do I test the code snippets in this tutorial?
Save each example as a .php file inside XAMPP htdocs folder, start Apache in XAMPP Control Panel, then open http://localhost/yourfile.php in a browser. For pure PHP CLI code, run php yourfile.php from the terminal.
Can I use this in a Laravel project?
Yes. Most native PHP functions covered in these tutorials work identically inside Laravel. Some Laravel helpers (str_helpers, arr_helpers) provide framework-specific wrappers around the same functions.
Where can I get more PHP practice projects?
Browse itsourcecode.com PHP Projects for 300+ free capstone-ready systems (POS, inventory, hospital management, e-commerce). Each includes source code, database SQL, and installation guide for BSIT capstone students.

Leave a Comment