Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to speed up cURL in php?

Tags:

rest

php

twitter

I'm trying to get embed tweet from Twitter. So, I'm using cURL to get the json back. I wrote a little test but the test takes around 5 seconds as well as when I run locally. So, I'm not sure what am I doing wrong here.

public function get_tweet_embed($tw_id) {

    $json_url = "https://api.twitter.com/1/statuses/oembed.json?id={$tw_id}&align=left&omit_script=true&hide_media=false";

    $ch = curl_init( $json_url );
    $start_time = microtime(TRUE);
    $JSON = curl_exec($ch);
    $end_time = microtime(TRUE);
    echo $end_time - $start_time; //5.7961111068726

    return $this->get_html($JSON);
}

private function get_html($embed_json) {
    $JSON_Data = json_decode($embed_json,true);
    $tw_embed_code = $JSON_Data["html"];
    return $tw_embed_code;
}

When I paste the link and test it from the browser it's really fast.

like image 731
toy Avatar asked Oct 19 '13 15:10

toy


People also ask

How can I make my hair cURL faster?

Use a curling iron if you want to control the size of the curls or use a straightener for a quick, easy option. To quickly curl thick hair, tie it in a ponytail before you curl the ends. You'll be done in a snap!

Is cURL faster than File_get_contents?

file_get_contents() is slightly faster than cURL.

How does PHP handle cURL request?

PHP cURL download file php $ch = curl_init('http://webcode.me'); $fp = fopen('index. html', 'w'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, false); curl_exec($ch); if (curl_error($ch)) { fwrite($fp, curl_error($ch)); } curl_close($ch); fclose($fp);

Is cURL asynchronous in PHP?

Short answer is no it isn't asynchronous. Longer answer is "Not unless you wrote the backend yourself to do so." If you're using XHR, each request is going to have a different worker thread on the backend which means no request should block any other, barring hitting process and memory limits.


1 Answers

The best speed up I've ever had was reusing the same curl handle. Replace $ch = curl_init( $json_url ); with curl_setopt($ch, CURLOPT_URL, $url);. Then outside the functions have one $ch = curl_init();. You'll need to make $ch global in the functions to access it.

Reusing the curl handle keeps the connection to the server open. This only works if the server is the same between requests, as yours are.

like image 172
Michael Ozeryansky Avatar answered Sep 30 '22 07:09

Michael Ozeryansky