Web Development

This part is of the PHP Post Series dedicated to spread knowledge about PHP

Deleting, creating and modifying files critical filesystem functionalities you can expect from programming languages.

PHP doesn’t want to get left down. Here are a few functionalities and tricks for deleting files.

Delete a single file

unlink('index.html');

Delete all files in a directory

// get all file names
$files = glob('path/to/folder/*');
// loop through files
foreach($files as $file){
  if(is_file($file)) {
    // delete file
    unlink($file);
  }
}
// A better alternative is to use the array_map function in conjunction with the glob function
array_map('unlink', glob("path/to/folder/*"));

Deleting certain file types

$jpeg_files = glob('path/to/folder/*.jpg');
// loop through files
foreach($jpeg_files as $file){
  if(is_file($file)) {
    // delete file
    unlink($file);
  }
}
// Alternative
array_map('unlink', glob("path/to/folder/*.jpg"));