PHP unlink() Function
Quick summary: The PHP unlink() function deletes a file.
PHP unlink() Syntax
unlink(string $filename, ?resource $context = null): bool
PHP
PHP unlink() Basic examples
file_put_contents('temp.txt', 'data');
var_dump(unlink('temp.txt'));
PHP
Output:
bool(true)
Deletes an existing file.
PHP unlink() Real-world usage
if (file_exists('cache.json')) {
unlink('cache.json');
echo 'Cache cleared';
}
PHP
Output:
Cache cleared
Removes cached files.
PHP unlink() Edge cases
var_dump(unlink('missing.txt'));
PHP
Output:
bool(false)
Returns false if the file does not exist.
PHP unlink() Common mistakes
Deleting files without checks
unlink fails if the file does not exist.
Incorrect
unlink('file.txt');
Correct
if (is_file('file.txt')) unlink('file.txt');
Check file existence before deleting.
PHP unlink() Frequently Asked Questions
What does unlink() do?
Deletes a file from the filesystem.
Does unlink() delete directories?
No, use rmdir() for directories.
Return value?
True on success, false on failure.
Use case?
Removing temporary or uploaded files.
Common mistake?
Trying to delete directories.
Can fail silently?
Yes, check return value.
Permissions required?
Yes.
Safe with user input?
Validate paths strictly.
Performance?
Fast.
Can delete open file?
Depends on OS.
Alternative?
Filesystem APIs.
Best practice?
Check file_exists() first.