What are best practices for handling errors and displaying error messages when using file_get_contents in PHP?

When using file_get_contents in PHP, it is important to handle errors properly and display meaningful error messages to the user. One common issue is not checking for errors when using file_get_contents, which can lead to unexpected behavior or security vulnerabilities. To solve this, you can use the error handling functions in PHP to check for errors and display appropriate messages to the user.

$url = 'https://www.example.com';

// Use file_get_contents with error handling
$content = @file_get_contents($url);
if ($content === false) {
    $error = error_get_last();
    echo "Error fetching content: " . $error['message'];
} else {
    // Process the content
    echo $content;
}