Using PHP curl to PUT a string to a web service

With PHP curl function it is easy to PUT a file to a web service. However doing a PUT on a string is a little trickier. This is how I did it in PHP v5.1.6:

// The message
$message = "My little string of characters";

// Get the curl resource handle
$session = curl_init("http://localhost/myservice");

// Prepare message for PUT
$put_data = tmpfile(); //Get temporary filehandle
fwrite($put_data, $message); //Write the string to the temporary file
fseek($put_data, 0); //Put filepointer to the beginning of the temporary file

// Set the POST options
curl_setopt($session, CURLOPT_PUT, true); // Use PUT
curl_setopt($session, CURLOPT_HEADER, true); // Send header
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // Get response
curl_setopt($session, CURLOPT_INFILE, $put_data); // Set string data
curl_setopt($session, CURLOPT_INFILESIZE, strlen($message)); //Set data size

// Do the PUT and show the response
$response = curl_exec($session);
echo $response;

This will simply write my string ($message) to a php temporary file ($put_data). I then use this file when sending the data to the web service. NOTE: CURLOPT_HEADER and CURLOPT_RETURNTANSFER are optional.

Comments are closed.

Niklas Tech Blog
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.