April
8th, 2008
RESTful PUT calls with PHP and Curl
UPDATE: There’s a faster way to do this over here.
Curl quickly becomes your best friend when working with web services. Unfortunately making PUT calls with PHP isn’t completely straight forward. Sure there’s CURLOPT_PUT but how do you attach a file that’s not really a file but a string in memory? Fortunately, PHP 5.2 introduces memory streams which can be treated as file handles.
How it’s done
Basically, we can store the string as a memory stream and pass that in to curl_setopt($ch, CURLOPT_INFILE). Let’s say you have an xml string stored in $xml. You want to PUT that to some REST web service endpoint, say http://example.com/ws/hello/world. You could do that using the following code.
$xml = 'Hello World! Watch me PUT this here. ‘; $fh = fopen(’php://memory’); fwrite($fh, $xml); rewind($fh); $ch = curl_init(’http://example.com/ws/hello/world’); curl_setopt($ch, CURLOPT_PUT, true); curl_setopt($ch, CURLOPT_INFILE, $fh); curl_setopt($ch, CURLOPT_INFILESIZE, strlen($xml)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); echo curl_exec($ch); curl_close($ch); fclose($fh);
More control with php://temp
PHP also has a temp stream which behaves similarly to the memory stream but gives you additional control in how much memory it’s allowed to take before writing the data to disk. This is very useful if you’re unsure what the size of the content you’re trying to PUT is.
$tenMB = 10 * 1024 * 1024;
$fh = fopen("php://temp/maxmemory:{$tenMB}");
PHP will automatically take care of managing wether or not it stays in memory (good) or goes to disk (bad - but good).
As always…comments welcome.
Resources
