What are some best practices for handling HTTP requests in PHP to avoid errors like "HTTP request failed"?

When handling HTTP requests in PHP, it's essential to properly handle errors to avoid issues like "HTTP request failed." One best practice is to use try-catch blocks to catch any exceptions that may occur during the request. Additionally, always check the response status code to ensure the request was successful before processing the response data.

try {
    $response = file_get_contents('https://api.example.com/data');
    
    if ($response === false) {
        throw new Exception('HTTP request failed');
    }
    
    // Process the response data here
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}