How to Delete ALL .txt files From a Directory using PHP How to Delete ALL .txt files From a Directory using PHP php php

How to Delete ALL .txt files From a Directory using PHP


Your Implementation works all you need to do is use Use full PATH

Example

$fullPath = __DIR__ . "/test/" ;array_map('unlink', glob( "$fullPath*.log"))


I expanded the submitted answers a little bit so that you can flexibly and recursively unlink text files located underneath as it's often the case.

// @param  string  Target directory// @param  string  Target file extension// @return boolean True on success, False on failurefunction unlink_recursive($dir_name, $ext) {    // Exit if there's no such directory    if (!file_exists($dir_name)) {        return false;    }    // Open the target directory    $dir_handle = dir($dir_name);    // Take entries in the directory one at a time    while (false !== ($entry = $dir_handle->read())) {        if ($entry == '.' || $entry == '..') {            continue;        }        $abs_name = "$dir_name/$entry";        if (is_file($abs_name) && preg_match("/^.+\.$ext$/", $entry)) {            if (unlink($abs_name)) {                continue;            }            return false;        }        // Recurse on the children if the current entry happens to be a "directory"        if (is_dir($abs_name) || is_link($abs_name)) {            unlink_recursive($abs_name, $ext);        }    }    $dir_handle->close();    return true;}


You could modify the method below but be careful. Make sure you have permissions to delete files. If all else fails, send an exec command and let linux do it

static function getFiles($directory) {    $looper = new RecursiveDirectoryIterator($directory);    foreach (new RecursiveIteratorIterator($looper) as $filename => $cur) {        $ext = trim($cur->getExtension());        if($ext=="txt"){           // remove file:         }    }    return $out;}