How can the sendToHost function be refactored to improve code readability, maintainability, and flexibility, especially when dealing with different HTTP methods and request types?

The sendToHost function can be refactored by creating a more flexible and maintainable solution using PHP's built-in cURL library. By utilizing cURL, we can easily handle different HTTP methods and request types, making the code more readable and adaptable to various scenarios.

function sendToHost($url, $method = 'GET', $data = []) {
    $ch = curl_init($url);

    if($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    }

    // Add more conditions for other HTTP methods if needed

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    curl_close($ch);

    return $response;
}

// Example usages
echo sendToHost('http://example.com/api', 'GET');
echo sendToHost('http://example.com/api', 'POST', ['key' => 'value']);