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'); ?>
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.
A1WEBSITEPRO Social Media Pages
Here are my social media pages, lets hook up!