W3docs

unlink()

In PHP, the unlink() function is used to delete a file. It is a useful function for working with files in your PHP scripts. In this article, we will cover

Introduction

The PHP unlink() function deletes a single file from the filesystem. The name comes from the underlying Unix system call unlink, which removes a name (a "link") pointing to a file's data. When the last link to a file is removed, the file itself is freed.

This chapter covers the syntax, return value, permission rules, and — just as important — the gotchas: silenced warnings, deleting only when a file exists, and why unlink() cannot remove directories.

Syntax

unlink(string $filename, ?resource $context = null): bool

Parameters

  • $filename — the path to the file to delete. It can be relative to the current working directory or an absolute path.
  • $context (optional) — a stream context resource, used for advanced cases such as deleting over a stream wrapper (e.g. FTP). You will rarely need it.

Return value

  • true if the file was deleted successfully.
  • false if it failed — for example, the file does not exist, the path points to a directory, or the process lacks permission. On failure PHP also emits an E_WARNING.

unlink() is the counterpart to functions that create files, such as fopen() and file_put_contents().

A basic example

Always check the return value so your script knows whether the deletion actually happened:

<?php
// Create a file so we have something to delete.
file_put_contents('example.txt', 'temporary data');

if (unlink('example.txt')) {
    echo "File deleted successfully.";
} else {
    echo "Failed to delete the file.";
}

Output:

File deleted successfully.

Delete only if the file exists

Calling unlink() on a missing file returns false and raises a warning. Guard the call with file_exists() (or is_file()) to avoid noisy warnings:

<?php
$path = 'cache/report.tmp';

if (file_exists($path)) {
    unlink($path);
    echo "Removed: {$path}";
} else {
    echo "Nothing to remove.";
}

If cache/report.tmp does not exist, this prints Nothing to remove. instead of triggering a warning.

Handling failures cleanly

In production you often want to react to a failed delete rather than crash. The @ operator suppresses the warning, but a cleaner approach is to check the result and report it yourself:

<?php
$path = 'logs/old.log';

if (!@unlink($path)) {
    // file_exists() distinguishes "already gone" from a real permission error.
    if (file_exists($path)) {
        echo "Could not delete {$path} — check permissions.";
    } else {
        echo "File was already gone.";
    }
}

Permissions: who can delete a file

A common surprise: permission to delete a file is controlled by the directory, not the file. To remove a file, the PHP process (e.g. the web-server user such as www-data) needs write and execute permission on the directory that contains it — even if the file itself is read-only. If you get "permission denied" failures, inspect the parent directory's permissions, not just the file's.

Deleting many files

unlink() removes one file at a time. To delete several files matching a pattern, combine it with glob():

<?php
// Delete every .tmp file in the cache directory.
foreach (glob('cache/*.tmp') as $file) {
    unlink($file);
}

glob() returns an array of matching paths (or an empty array if none match), so the loop simply does nothing when there is nothing to delete.

unlink() only works on files. If you pass it a directory, it fails and warns. To remove a directory, use rmdir() — and note that rmdir() only works on an empty directory. Removing a non-empty directory means deleting its contents first (with unlink() for files and rmdir() for sub-directories), then removing the directory itself.

Common gotchas

  • The file must exist. A missing file returns false and warns. Check with file_exists() first.
  • It is permanent. unlink() does not move the file to a trash/recycle bin; the data is gone immediately.
  • Not for directories. Use rmdir() for directories.
  • Stat cache. After deleting a file, PHP may still report it as existing because of the stat cache. Call clearstatcache() if you re-check the same path in a tight loop.
  • Open file handles. On Windows you cannot delete a file that is still open; close it with fclose() first. On Unix the delete is allowed, but the data stays until the last handle closes.

Conclusion

unlink() is PHP's straightforward way to delete a single file, returning true on success and false (plus a warning) on failure. The key practices are: check whether the file exists before deleting, always inspect the return value, remember that delete permission depends on the directory, and reach for rmdir() when you need to remove directories. For a broader picture of reading, writing, and managing files, see PHP File Handling.

Practice

Practice
What is the function of 'unlink()' in PHP?
What is the function of 'unlink()' in PHP?
Was this page helpful?