PHP Developer / Blog

April
23rd, 2008

A faster way to do curl put calls in PHP

Digg this article · Save to del.icio.us · Stumble it!

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

2 Responses to “A faster way to do curl put calls in PHP”

  1. Kevin Says:

    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.

  2. jaisen Says:

    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.

Leave a Reply

Captcha
Enter the letters you see above.


About this site:
This is my (Jaisen Mathai) personal site for potential employers who want to see my resume or portfolio. My ideal job would be to work as a PHP developer on a large scale consumer website. My experience is in using PHP, MySQL, Ajax and JSON. I really enjoy creative brainstorming...taking a problem apart and narrowing 100 solutions down to the best one.

Thanks for stopping by. Be sure to drop me a line.