Skip to content

Instantly share code, notes, and snippets.

@guanguans
Forked from kinlane/long-running-curl-sse.php
Created December 16, 2022 09:48
Show Gist options
  • Save guanguans/a2ac5c9780ae238be7aa6952966b76d9 to your computer and use it in GitHub Desktop.
Save guanguans/a2ac5c9780ae238be7aa6952966b76d9 to your computer and use it in GitHub Desktop.
Long Running PHP CURL Requests To Handle Server Sent Events (SSE)
<?php
// prepare headers for API call
$request_headers = array();
// prepare the url of the api I am calling
$api_url = "http://api.example.com?parameters=whatever";
// append streamdata sandbox proxy
$url = 'https://streamdata.motwin.net/' . $api_url;
// setup the api request
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'myfunc');
// if there are any headers, add them to request
if(count($request_headers) > 0)
{
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
}
$result = curl_exec($ch);
curl_close($ch);
// this function gets run for each request
function myfunc($ch, $data)
{
// how big is the data transmission
$bytes = strlen($data);
static $buf = '';
$buf .= $data;
// Collect the details of each transmission
$info = curl_getinfo($ch);
$http_code = $info['http_code'];
$total_time = $info['total_time'];
$namelookup_time = $info['namelookup_time'];
$connect_time = $info['connect_time'];
$size_download = $info['size_download'];
$speed_download = $info['speed_download'];
$download_content_length = $info['download_content_length'];
while(1)
{
$pos = strpos($buf, "\n");
if($pos === false)
{
break;
}
// trim things down
$data = substr($buf, 0, $pos+1);
$buf = substr($buf, $pos+1);
// only log if there is something there
if(strlen($data)>50)
{
// remove data: prefix
$results = str_replace("data:","",$data);
// Log the details of the transaction to Amazon S3 (or other)
// Log the content of the transaction to Amazon S3 (or other)
}
}
// this is important!
// won't run if we don't return exact size
return $bytes;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment