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

5

9

Im trying to Delete ALL Text files from a directory using a php script.

Here is what I have tried.....

<?php array_map('unlink', glob("/paste/*.txt")); ?>

I dont get an Error when I run this, yet It doesnt do the job.

Is there a snippet for this? Im not sure what else to try.

Nijinsky answered 13/10, 2012 at 3:13 Comment(4)
There isnt an error, I said that above.Nijinsky
Is the path /paste/*.txt right ? The paste dir is under /Douro
Baba Helped me, I wasnt using the Full Path, I had to inlude /home/user/ ect... I Got it now, have to wait to accept his answer.Nijinsky
You should know you are using the full path, the problem is you are using the wrong full path. Any path start with / is a full path.Douro
Q
28

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

Example

$fullPath = __DIR__ . "/test/" ;
array_map('unlink', glob( "$fullPath*.log"))
Quigley answered 13/10, 2012 at 3:15 Comment(1)
Thanks Man, I Didn't know what the prob was, Thanks for clearing it up for me.Nijinsky
U
3

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 failure

function 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;

}
Unbelt answered 13/10, 2012 at 9:35 Comment(0)
R
1

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;
}
Refresh answered 13/10, 2012 at 3:23 Comment(0)
B
1

i have modified submitted answers and made my own version,

in which i have made function which will iterate recursively in current directory and its all child level directories,

and it will unlink all the files with extension of .txt or whatever .[extension] you want to remove from all the directories, sub-directories and its all child level directories.

i have used : glob() From the php doc:

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

i have used GLOB_ONLYDIR flag because it will iterate through only directories, so it will be easier to get only directories and unlink the desired files from that directory.

<?php

//extension of files you want to remove.
$remove_ext = 'txt';
//remove desired extension files in current directory
array_map('unlink', glob("./*.$remove_ext"));

// below function will remove desired extensions files from all the directories recursively.
function removeRecursive($directory, $ext) {

    array_map('unlink', glob("$directory/*.$ext"));

    foreach (glob("$directory/*",GLOB_ONLYDIR) as $dir) {
            removeRecursive($dir, $ext);
    }
    return true;
}

//traverse through all the directories in current directory 
foreach (glob('./*',GLOB_ONLYDIR) as $dir) {
    removeRecursive($dir, $remove_ext);
}

?>
Backpedal answered 15/5, 2019 at 13:28 Comment(0)
S
1

For anyone who wonder how to delete (for example: All PDF files under public directory) you can do this:

array_map('unlink', glob( public_path('*.pdf')));
Slip answered 29/8, 2020 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.