The put
method takes two parameters, the service URL and data to be put to the service.
public function put($url, $data) {
While using PUT
with CURL, we need to have a file handler with the data to be sent to service with PUT
. So we create a file handler in memory first and then write the data given by the user to that file handler.
$fh = fopen('php://memory', 'rw');
fwrite($fh, $data);
rewind($fh);
Then we put that data to the service using CURL.
$curl = curl_init(); curl_setopt($curl, CURLOPT_USERAGENT, RESTClient :: USER_AGENT); curl_setopt($curl, CURLOPT_INFILE, $fh); curl_setopt($curl, CURLOPT_INFILESIZE, strlen($data)); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_setopt($curl, CURLOPT_PUT, 1); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); curl_close($curl); fclose($fh);
If CURL is not present, we again use fopen
to handle the PUT
request.
} else { $opts = array ( 'http' => array ( 'method' => "PUT", '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); }