What are some best practices for handling file inclusions and content display in PHP to prevent server-side attacks?

One best practice for handling file inclusions and content display in PHP to prevent server-side attacks is to always sanitize user input and validate file paths before including them. This helps prevent directory traversal attacks and unauthorized access to sensitive files. Additionally, it's important to avoid displaying sensitive information in error messages to avoid leaking information to potential attackers.

// Sanitize and validate file paths before including them
$filename = 'path/to/file.php';
if (strpos($filename, '..') === false && file_exists($filename)) {
    include $filename;
} else {
    // Handle invalid file path or unauthorized access
    echo 'Invalid file path';
}

// Avoid displaying sensitive information in error messages
ini_set('display_errors', 0);
error_reporting(0);