Alex saw, in the company's codebase, a method called recursive_readdir. It had no comments, but the name seemed pretty clear: it would read directories recursively, presumably enumerating their contents.

Fortunately for Alex, they checked the code before blindly calling the method.

public function recursive_readdir($path)
{
    $handle = opendir($path);
    while (($file = readdir($handle)) !== false)
    {
        if ($file != '.' && $file != '..')
        {
            $filepath = $path . '/' . $file;
            if (is_dir($filepath))
            {
                rmdir($filepath);
                recursive_readdir($filepath);
            }
            else
            {
                    unlink($filepath);
            }
        }
    }
    closedir($handle);
    rmdir($path);
}

This is a recursive delete. rmdir requires the target directory to be empty, so this recurses over all the files and subfolders in the directory, deleting them, so that we can delete the directory.

This code is clearly cribbed from comments on the PHP documentation, with a fun difference in that this version is both unclearly named, and also throws an extra rmdir call in the is_dir branch- a potential "optimization" that doesn't actually do anything (it either fails because the directory isn't empty, or we end up calling it twice anyway).

Alex learned to take nothing for granted in this code base.

[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!