Deleting a directory owned by 'nobody'

From A2Wiki

Jump to: navigation, search

When a script creates files and/or directories on the server, they are owned by the user/group 'nobody'. Any script running on the server or interacting with the server is identified as the user 'nobody', so 'nobody' owns the files that it creates. You cannot modify or change permissions on these files because they are not owned by you.

What you can do, however is leverage some PHP code to do the deleting for you. The unlink() funtion in PHP is used for deleting items, and because a PHP script run through a web browser is executed as the user 'nobody' this can delete files owned by nobody as well.

Many times you might have a directory that needs to be periodically deleted, say for example a temporary thumbnails directory. Creating a php file with the code below, and calling it, for example deletetemp.php would allow you to do this. Once you've created this file, simply load it in a browser, (at for example yourdomain.com/deletetemp.php) and this will give you the message 'all done.' and the directory specified should be deleted.

<?php

define('PATH', './directoryToDelete/');
 
function destroy($dir) {
    $mydir = opendir($dir);
    while(false !== ($file = readdir($mydir))) {
        if($file != "." && $file != "..") {
            chmod($dir.$file, 0777);
            if(is_dir($dir.$file)) {
                chdir('.');
                destroy($dir.$file.'/');
                rmdir($dir.$file) or DIE("couldn't delete $dir$file<br />");
            }
            else
                unlink($dir.$file) or DIE("couldn't delete $dir$file<br />");
        }
    }
    closedir($mydir);
}
destroy(PATH);
echo 'all done.'; 

?>
Personal tools