The get
member function of RESTClient
class takes two parameters, the URL of the service and the request parameters.
public function get($url, $params) {
And it builds the request URL to include the request parameters.
$params_str = "?"; if (is_array($params)) { foreach ($params as $key => $value) { $params_str .= urlencode($key) . "=" . urlencode($value) . "&"; } } else { $params_str .= $params; } $url .= $params_str;
And if CURL is available, it would send a GET
request using CURL.
if ($this->with_curl) { $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_HTTPGET, TRUE); curl_setopt($curl, CURLOPT_USERAGENT, RESTClient :: USER_AGENT); $result = curl_exec($curl); curl_close($curl); }
We are already familiar with the constructs used in the above method that were discussed in Chapter 2.
If CURL is not available, we would be using fopen
function to send the GET
request and fetch the result.
} else { $opts = array ( 'http' => array ( 'method' => "GET", 'header' => "User-Agent: " . RESTClient :: USER_AGENT . "\r\n" ) ); $context = stream_context_create($opts); $fp = fopen($url, 'r', false, $context); $result = fpassthru($fp); fclose($fp); }
In here, we use the options to be used with the HTTP request such as the HTTP method GET
and user agent header. We then create a context with those options and open the URL with fopen
, using the context created.