What are some best practices for automatically reading the filesystem into a database in PHP?

When automatically reading the filesystem into a database in PHP, it's important to use a recursive function to scan through directories, gather file information, and insert it into the database efficiently. It's also crucial to handle file permissions, error handling, and database connections properly to ensure the process runs smoothly.

<?php
// Function to recursively scan a directory and insert file information into a database
function scanDirectory($dir, $pdo) {
    $files = scandir($dir);
    
    foreach($files as $file) {
        if ($file != '.' && $file != '..') {
            $filePath = $dir . '/' . $file;
            if (is_dir($filePath)) {
                scanDirectory($filePath, $pdo);
            } else {
                $fileInfo = pathinfo($filePath);
                $stmt = $pdo->prepare("INSERT INTO files (filename, path, extension) VALUES (:filename, :path, :extension)");
                $stmt->execute(array(
                    ':filename' => $fileInfo['filename'],
                    ':path' => $filePath,
                    ':extension' => $fileInfo['extension']
                ));
            }
        }
    }
}

// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=your_database', 'username', 'password');

// Specify the directory to scan
$directory = '/path/to/directory';

// Call the function to scan the directory and insert file information into the database
scanDirectory($directory, $pdo);
?>