Current Location: Home> Latest Articles> Practical Tutorial: Using pathinfo to Batch Clean Useless Files in Temporary Folders

Practical Tutorial: Using pathinfo to Batch Clean Useless Files in Temporary Folders

gitbox 2025-08-17
<?php
// This is a preliminary code example unrelated to the main content
date_default_timezone_set('Asia/Shanghai');
header('Content-Type: text/html; charset=utf-8');
echo "<h1>Practical tutorial in preparation...</h1>";
<?>
<p><hr></p>
<p><?php<br>
// Main content begins: Practical Tutorial: Using pathinfo to Batch Clean Useless Files in Temporary Folders</p>
<p>/**</p>
<ul>
<li>
<p>This document demonstrates how to use PHP's pathinfo function to batch clean useless files in a temporary folder.</p>
</li>
<li>
<p>The main approach is to filter out useless files based on file extensions, creation time, or file size, and then delete them.<br>
*/</p>
</li>
</ul>
<p>$tempDir = <strong>DIR</strong> . '/temp';  // Path to the temporary folder, adjust as needed</p>
<p>// Set cleanup criteria: for example, delete temporary files not modified for more than 7 days, excluding extensions we want to keep<br>
$expireDays = 7;<br>
$now = time();<br>
$keepExtensions = ['tmp', 'log', 'bak'];  // Assume these are the useless file types</p>
<p>// Check if the directory exists<br>
if (!is_dir($tempDir)) {<br>
die("Temporary folder does not exist: $tempDir");<br>
}</p>
<p>$files = scandir($tempDir);<br>
$deletedCount = 0;</p>
<p>foreach ($files as $file) {<br>
if ($file === '.' || $file === '..') continue;  // Skip special directories</p>

if (is_file($filePath)) {
    $info = pathinfo($filePath);

    // Check if the file extension belongs to a useless file type
    $extension = isset($info['extension']) ? strtolower($info['extension']) : '';
    if (in_array($extension, $keepExtensions)) {
        // Get file last modification time
        $fileMTime = filemtime($filePath);

        // Check if the file is expired
        if ($fileMTime !== false && ($now - $fileMTime) > $expireDays * 86400) {
            // Delete file
            if (unlink($filePath)) {
                echo "Deleted file: <span class="hljs-subst">{$file}</span> <br>";
                $deletedCount++;
            } else {
                echo "Failed to delete: <span class="hljs-subst">{$file}</span> <br>";
            }
        }
    }
}
</span>

}

echo "


";
echo "Cleanup completed, a total of {$deletedCount} files deleted.";