What are some best practices for handling URLs in PHP functions like file_get_contents()?

When using functions like file_get_contents() in PHP to fetch URLs, it is important to properly handle potential errors and exceptions that may occur during the process. One best practice is to use error handling functions like try-catch blocks to catch any exceptions and handle them gracefully, such as displaying an error message to the user or logging the error for debugging purposes.

try {
    $url = 'https://example.com';
    $data = file_get_contents($url);
    
    if ($data === false) {
        throw new Exception('Failed to fetch URL');
    }
    
    // Process the fetched data here
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}