How can one send a valid server request in PHP to avoid the "HTTP request failed" error?

When sending a server request in PHP, it is important to handle potential errors such as the "HTTP request failed" error. To avoid this error, you can use the try-catch block to catch any exceptions that may occur during the request. By doing so, you can handle the error gracefully and prevent it from crashing your application.

try {
    $response = file_get_contents('http://example.com/api');
    // Process the response data here
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}