restricted version (protect certain files)

blindly deleting everything is risky. A restricted cleaner gives you control.

Here’s a production-safe PHP script that:

  • Deletes everything inside /tmp/
  • Protects specific files/folders
  • ✅ Optional: protect by extension
  • ✅ Optional: delete only older files
<?php

function deleteRestricted($dir, $protectedNames = [], $protectedExtensions = [], $maxAgeSeconds = null) {
    if (!is_dir($dir)) {
        return;
    }

    $files = scandir($dir);

    foreach ($files as $file) {
        if ($file === "." || $file === "..") {
            continue;
        }

        $fullPath = $dir . '/' . $file;

        // 🔒 Skip protected file/folder names
        if (in_array($file, $protectedNames)) {
            continue;
        }

        // 🔒 Skip protected extensions
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        if (!empty($protectedExtensions) && in_array($ext, $protectedExtensions)) {
            continue;
        }

        // ⏳ Skip files newer than allowed age
        if ($maxAgeSeconds !== null && file_exists($fullPath)) {
            if (time() - filemtime($fullPath) < $maxAgeSeconds) {
                continue;
            }
        }

        if (is_dir($fullPath)) {
            deleteRestricted($fullPath, $protectedNames, $protectedExtensions, $maxAgeSeconds);
            // Remove folder only if empty
            if (count(scandir($fullPath)) == 2) {
                rmdir($fullPath);
            }
        } else {
            unlink($fullPath);
        }
    }
}


// ================= CONFIG =================

// Target directory
$targetDir = '/home/uhmn6p9kb8ir/tmp/';

// Protect specific file/folder names
$protectedNames = [
    'index.php',
    '.htaccess',
    'keep_this_folder'
];

// Protect file extensions (example: logs, configs)
$protectedExtensions = [
    'log',
    'txt'
];

// Delete only files older than 1 hour (3600 sec)
// Set NULL to delete all (except protected)
$maxAgeSeconds = 3600;


// ================= RUN =================

deleteRestricted($targetDir, $protectedNames, $protectedExtensions, $maxAgeSeconds);

echo "Restricted cleanup completed safely.";

?>

🧠 What this script does

  • Keeps:
    • index.php, .htaccess, keep_this_folder
    • All .log and .txt files
    • Files newer than 1 hour
  • Deletes everything else safely

🔥 Pro Tips (Important)

  • Always keep a dummy index.php in /tmp/
  • Add .htaccess: deny from all
  • Test first by replacing unlink() with: echo “Deleting: $fullPath\n”; (dry-run mode)