00 Votes

PHP: Delete a File

Question by Guest | Last update on 2021-01-13 | Created on 2015-11-04

I would like to delete a file stored on my server out of my PHP script.

Is there any function to do that available in PHP? Or if that is not easy to implement?

ReplyPositiveNegativeDateVotes
0Best Answer0 Votes

You are searching for the function unlink(), to which you can just pass the filename of the file that should be deleted.

For example, you can use the function like that:

$f = 'test.dat';

if (file_exists($f)) {
   unlink($f);
} else {
   echo 'File not found!';
}

In this example, first we are using the function file_exists() to check whether the file "test.dat" exists. If yes, we are deleting the file using unlink().
Last update on 2021-01-13 | Created on 2015-11-04

ReplyPositive Negative
00 Votes

Here is another small example for using the unlink() function provided by PHP:

$fh = fopen('test.txt', 'a');
fwrite($fh, 'Content of File');
fclose($fh);

unlink('test.txt');

First, we are creating a simple text file called "test.txt" and after that, we are writing "Content of File" into the file. Then, we are immediately deleting the file using the function unlink().
2015-11-04 at 23:54

ReplyPositive Negative
Reply

Related Topics

Rename File to its Folder Name

Tutorial | 0 Comments

PHP: File Download Script

Tutorial | 0 Comments

PHP: Upload of large Files

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.