Php Programming Code Examples
Php > File Manipulation Code Examples
Directory cleanup
Directory cleanup
<?PHP
$dir2clean = 'cache';
$test = false;
$more = false;
$output = '';
if ($handle = opendir($dir2clean))
{
$header = "\n";
$i = 0;
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle)) && $i < 105)
{
if ( $i < 100)
{
$output .= "<tr><td>$file</td>\n<td>";
if (substr($file, 0, 1) != '.')
{
if ($test) $output .= 'test';
elseif (unlink("{$dir2clean}/{$file}")) $output .= "deleted";
else $output .= "kept";
}
else $output .= ' ';
$output .= "</td><td>";
$output .= date ("F d Y H:i:s.", fileatime("cache/{$file}"));
$output .= "</td>\n</tr>\n";
}
else $more = true;
$i++;
}
closedir($handle);
}
?>
<html>
<head>
<?PHP
// meta refresh can fail in Internet Explorer but this works like a rocket in Firefox
if ($more && !$test)
{
echo "\n<META HTTP-EQUIV='Refresh' CONTENT=\"1; URL=http://{$_SERVER['HTTP_HOST']}{$PHP_SELF}\">\n";
}
?>
</head>
<body>
<h2>Date: <?php echo date('d-m-Y H:i'); ?><br />
Directory: <?=$dir2clean; ?><br />
Files:</h2>
<table border='1' cellpadding="4" cellspacing="0">
<?php echo $output; ?>
</table>
</body>
</html>