PHP gurus. I know this can be made shorter but I can't seem to figure out
how.

This is a PHP CLI script I use to go through a directory listing a act upon
file matching the same prefix and/or suffix if supplied. This is the code I
use now.

// set up the prefix and/or suffix if I want to match on certain files
$deleteprefix = "";
$deletesuffix = "";

// Open the folder
$dir_handle = @opendir($rootpath) or die("Unable to open ".$rootpath." hot
folder\n");

// Loop through the files
while ($file = readdir($dir_handle)) {
    
    if (substr($file,0,1) <> ".") {
            // tests
            if (($deleteprefix == "") and ($deletesuffix == "")) {
                // if both are empty just send anything
                logger("Deleted: ".$file." Last Modified: ".date("F j, Y
",filemtime($rootpath.$file)));
                unlink($rootpath.$file);
            } elseif (($deleteprefix != "") and ($deletesuffix != "")) {
                // if both have something test both
                if ((substr($file,0,strlen($deleteprefix)) == $deleteprefix)
and (substr($file,-strlen($deletesuffix)) == $deletesuffix)) {
                    logger("Deleted: ".$file." Last Modified: ".date("F j, Y
",filemtime($rootpath.$file)));
                    unlink($rootpath.$file);
                }
            } elseif (($deleteprefix == "") and ($deletesuffix != "")) {
                // if prefix is empty but suffix is not
                if (substr($file,-strlen($deletesuffix)) == $deletesuffix) {
                    logger("Deleted: ".$file." Last Modified: ".date("F j, Y
",filemtime($rootpath.$file)));
                    unlink($rootpath.$file);
                }
            } elseif (($deleteprefix != "") and ($deletesuffix == "")) {
                // if suffix is empty but prefix is not
                if (substr($file,0,strlen($deleteprefix)) == $deleteprefix)
{
                    logger("Deleted: ".$file." Last Modified: ".date("F j, Y
",filemtime($rootpath.$file)));
                    unlink($rootpath.$file);
                }
            }
            
        }
}

As you can see I test the filename 4 times depending on if the prefix or
suffix was supplied. Can somebody help me make this shorter? I don't think
all those tests are necessary if I could figure out the syntax.

DMyers

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to