Amit Verma
Amit Verma

Reputation: 41219

removing multiple files from a web-directory using foreach() function

I want to delete multiple files from my directory, and for this I am using the following code

$x=array(".index.php",".code.html","about.txt");
 foreach($x as $a)
 unlink($a);

The wired thing with this code is that it sometime works and sometimes doesn't, and no errors.

Is there anything that I am missing?

Upvotes: 0

Views: 43

Answers (1)

Marco Bernardini
Marco Bernardini

Reputation: 705

Add some monitoring to your code, to see what happens:

foreach($x as $a) {
    echo "File $a ";
    if (file_exists($a)) {
        if (is_file($a)) {
            echo "is a regular file ";
        } else {
            echo "is not a regular file ";
        }
        if (is_link($a)) {
            echo "is a symbolic link ";
        }
        if (is_readable($a)) {
            echo " readable";
        } else {
            echo " NOT readable";
        }
        if (is_writeable($a)) {
            echo " and writeable ";
        } else {
            echo " and NOT writeable ";
        }
        echo "owned by ";
        echo posix_getpwuid(fileowner($a)) ['name'];
        if (unlink($a)) {
            echo "- was removed<br />\n";
        } else {
            echo "- was NOT removed<br />\n";
        }
    } else {
        echo "doesn't exist<br />\n";
    }
}

Also read this comment on the PHP manual page about unlinking files.

If you have to use a path for your file, convert it to a real path with the function realpath() - see https://php.net/manual/en/function.realpath.php

Upvotes: 2

Related Questions