Trusted answers to developer questions

What is the unlink() function in PHP?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

The unlink function in PHP deletes a file. However, it should not be confused with the unset function in PHP, which is used to empty the file rather than delete it. The general syntax for the unlink function is:

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

Parameters

The unlink function has one compulsory parameter and one optional parameter. filename is the name of the file you wish to delete and is compulsory. The context parameter is optional and sets the behavior of the stream.

Return value

The unlink function returns true upon successfully deleting a file. However, if it fails, it will generate an E_Warning.

Example

The following example will help you understand the unlink function better. As shown below, the file main.txt is opened for writing and then closed using the fopen, fwrite, and fclose functions. Then, we use the unlink function and print its return value, demonstrating that the file has been successfully deleted.

<?php
$file = fopen("main.txt","w");
fwrite($file,"File testing");
fclose($file);
echo(unlink("main.txt"));
?>

RELATED TAGS

php

CONTRIBUTOR

Samia Ishaque
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?