K. Weber
K. Weber

Reputation: 2773

curl through an already open socket

I wonder if there's a way to use curl trhough an already open socket, something like, adapting this:

<?php
$fp = fsockopen("www.example.com", 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    $out = "GET / HTTP/1.1\r\n";
    $out .= "Host: www.example.com\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

to use curl_exec() instead of fgets($fp, 128)

(or, any other way to use curl() over the same stream all the time, my goal is to read the twitter stream api)

Thank you

Upvotes: 2

Views: 6111

Answers (2)

Baba
Baba

Reputation: 95161

This might work for you since you are dealing with Twitter Stream API

set_time_limit(0);
$ch = curl_init();
echo "<pre>";
curl_setopt($ch, CURLOPT_URL, "https://sitestream.twitter.com/2b/site.json");
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'cgets');
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);
curl_setopt($ch, CURLOPT_USERPWD, 'user:password');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 1000000);
curl_exec($ch);

function cgets($ch, $string) {
    $length = strlen($string);
    printf("Received %d byte\n", $length);
    flush();
    return $length;
}

Upvotes: 2

Jakub Wasilewski
Jakub Wasilewski

Reputation: 2976

There is no way to force cURL to use an existing socket in PHP. While cURL pools and reuses the connections internally, it cannot be forced to use the same one all the time, or never close a connection it opened.

You can checkout Phirehose (which is a PHP interface to the streaming APIs) or if that's not good enough, do some shopping on the Twitter Libraries list - chances are somebody already solved your problem in PHP and packaged it.

Still, using the stream API sound strange from PHP. Is this on a web server, or a stand-alone long-running script?

Upvotes: 0

Related Questions