How can PHP be used to identify and delete orphaned files in an upload directory?

Orphaned files in an upload directory are files that do not have corresponding entries in a database or any other reference system. To identify and delete these files using PHP, you can iterate through all files in the upload directory and check if each file is referenced in your database. If a file is not found in the database, it can be safely deleted.

<?php
// Define the upload directory
$uploadDir = 'path/to/upload/directory';

// Connect to your database
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Get list of files in the upload directory
$files = scandir($uploadDir);

// Loop through each file
foreach($files as $file){
    if($file != '.' && $file != '..'){
        // Check if file is referenced in the database
        $stmt = $pdo->prepare("SELECT * FROM your_table WHERE file_name = :file");
        $stmt->bindParam(':file', $file);
        $stmt->execute();
        
        if($stmt->rowCount() == 0){
            // File is orphaned, delete it
            unlink($uploadDir . '/' . $file);
            echo "Deleted orphaned file: $file <br>";
        }
    }
}
?>