April
23rd, 2008
A faster way to do curl put calls in PHP
In a previous post I suggested using PHP’s memory stream to pass data along with PUT calls in curl. After doing some benchmarking it turns out that it’s faster to use PHP’s CURLOPT_CUSTOMREQUEST option. This way you can treat PUT and POST calls in the same manner.
$ch = curl_init(); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, 'body goes here');
Just how much faster is it?
Using the following script I found that this method is over 70% faster than the one I had mentioned previously.
$ch = curl_init();
$xml = 'sss';
$s = microtime(true);
for($i=0; $i<1000000; $i++)
{
$fh = fopen('php://memory', 'w+');
fwrite($fh, $xml);
rewind($fh);
curl_setopt($ch, CURLOPT_INFILE, $fh);
fclose($fh);
}
$e = microtime(true);
$res = $e-$s;
echo "First option took {$res} seconds\n";
$s = microtime(true);
for($i=0; $i<1000000; $i++)
{
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
}
$e = microtime(true);
$res = $e-$s;
echo "Second option took {$res} seconds\n";
/*
Output
First option took 3.6376910209656 seconds
Second option took 2.1203410625458 seconds
*/
Nonetheless there will definitely be some other scenario where memory streams come in hand. Have a better way to do this? …. Comments.
Resources

April 24th, 2008 at 11:53 am
What are the benchmarks if you move the opening, closing, and rewinding of the file outside the first for loop? I understand this is part of the process, but you are doing that 1 million times in the first case, which seems a bit unfair since in general you will only be doing that file processing once. Which CURL method, itself, is actually faster.
April 30th, 2008 at 10:27 pm
If you’re just talking about the curl functions then I presume they’d be nearly identical. Doing it a million times was more to simulate an extremely high amount of traffic which is the only case where it would make a difference anyways.
But to your original point…without doing benchmarks my guess is that they’d be nearly identical if you didn’t have the fopen functions.