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.

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" line="" escaped="" cssfile="">

This site uses Akismet to reduce spam. Learn how your comment data is processed.