Delete Files in Directory or Folder With PHP | How To Tutorial | Unlink

To delete files in a directory or folder with PHP, all you have to do is use the unlink function. Unlink not only deletes pictures, but will delete any kind of file in a directory. Lets get started.

Unlink in PHP

The unlink function has been around since PHP4. It also works on PHP5, PHP7 and PHP8. Here is a basic example of using PHP to create a file, then delete it. The following code will create a file called test.html that has the H1 tag in it with “Hello World” then it immediately deletes it using the unlink function.

<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);

unlink('test.html');
?>

 

Only cool people share!

Removing Directories in PHP

Alternatively, you can remove and entire directory in PHP. Check out the example code below from php.net. Here we check if the directory “uploads” is created, if not then we create it. We use this in our script to make our uploads’ folder. However, in the script below we use the “rmdir” function to delete the directory.

<?php
if (!is_dir('uploads')) {
    mkdir('uploads');
}

rmdir('uploads');
?>

OK lets get on with the script to upload and delete files.

Delete Files in Directory or Folder With PHP | How To Tutorial | Unlink was last modified: October 22nd, 2022 by Maximus Mccullough
Summary
Delete Files in Directory or Folder With PHP | How To Tutorial | Unlink
Article Name
Delete Files in Directory or Folder With PHP | How To Tutorial | Unlink
Description
To delete files in a directory or folder with PHP, all you have to do is use the unlink function. Unlink not only deletes pictures, but will delete any kind of file in a directory.
Author
Publisher
A1WEBSITEPRO LLC
Logo
Delete Files in Directory or Folder With PHP

Pages: 1 2 Next

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.