The post
method takes three parameters, the service URL, data to be posted and an optional third parameter that specifies the content type.
public function post($url, $data, $content_type = "application/x-www-form-urlencoded") {
If CURL is available, the given data would be posted to the given service URL.
if ($this->with_curl) { $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, Array ( "Content-Type: " . $content_type )); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, TRUE); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_USERAGENT, RESTClient :: USER_AGENT); $result = curl_exec($curl); curl_close($curl); }
We set the content type as an HTTP header. So if the user of the class provided a custom content type that would be reflected in the request sent to the service. Again, the CURL POST
syntax used in this method was discussed in Chapter 2 in detail.
If CURL is not available, as in the case of get
method, we use fopen
to get the job done.
} else { $opts = array ( 'http' => array ( 'method' => "POST", 'header' => "User-Agent: " . RESTClient :: USER_AGENT . "\r\n" . "Content-Type: " . $content_type . "\r\n" . "Content-length: " . strlen($data ) . "\r\n", 'content' => $data )); $context = stream_context_create($opts); $fp = fopen($url, 'r', false, $context); $result = fpassthru($fp); fclose($fp); }