Thursday, June 25, 2015

PHP CURL PUT json with username password

Recently I faced a lot of difficulty in requesting a put to RESTful service. If you have faced the similar issue to PUT to a RESTful service with username password, here is a sample snippet. Hope this helps. 

$file_contents_string = file_get_contents("");
$request = curl_init();
curl_setopt($request, CURLOPT_URL, "http://dummyhost:dummyport/");
curl_setopt($request, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', 'Content-Length: ' . strlen($file_contents_string)));
curl_setopt($request, CURLOPT_POSTFIELDS, $file_contents_string);
curl_setopt($request, CURLOPT_USERPWD, "$username:$password");
curl_setopt($request, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($request, CURLOPT_VERBOSE, true);
// output the response
var_dump(curl_exec($request));

No comments:

Post a Comment