Deleting all files from a folder using PHP?

✔ Recommended Answer

$files = glob('path/to/temp/*'); // get all file namesforeach($files as $file){ // iterate files  if(is_file($file)) {    unlink($file); // delete file  }}

If you want to remove 'hidden' files like .htaccess, you have to use

$files = glob('path/to/temp/{,.}*', GLOB_BRACE);

Source: stackoverflow.com

Answered By: Floern

Method #2

To delete all files from a folder using PHP, you can use the glob() function to get a list of all files in the folder, and then use the unlink() function to delete each file one by one.

Here's an example:

php
$files = glob('/path/to/folder/*'); // Get all files in folder foreach ($files as $file) { if (is_file($file)) { // Check if file unlink($file); // Delete file } }

In this example, we're using the glob() function to get a list of all files in the folder specified by the path /path/to/folder/*. This will return an array of file paths, which we loop through using a foreach loop.

For each file path in the array, we check if it's a file using the is_file() function. If it is a file, we delete it using the unlink() function.

Note that this code will only delete files, not folders. If you want to delete a folder and all its contents, you can use the rmdir() function, but be careful as this will delete all files and subfolders inside the folder as well.

Comments

Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Remove Unicode Zero Width Space PHP

Laravel file upload returns forbidden 403, file permission is 700 not 755