How can PHP users filter and output logs from specific directories in a secure and efficient manner?

When filtering and outputting logs from specific directories in PHP, users can use the opendir() function to open a directory handle, iterate through the files using readdir(), and filter based on file extensions or other criteria. To ensure security, users should validate and sanitize user input to prevent directory traversal attacks. Additionally, users can implement error handling to handle any potential issues that may arise during the process.

$directory = "path/to/logs/";
if ($handle = opendir($directory)) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != ".." && pathinfo($file, PATHINFO_EXTENSION) == 'log') {
            echo "Log file: $file\n";
        }
    }
    closedir($handle);
} else {
    echo "Error opening directory";
}