php 长期运行PHP CURL请求以处理服务器发送事件(SSE)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 长期运行PHP CURL请求以处理服务器发送事件(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;
  }
?>

以上是关于php 长期运行PHP CURL请求以处理服务器发送事件(SSE)的主要内容,如果未能解决你的问题,请参考以下文章

PHP通过curl向其它服务器发请求并返回数据

PHP:CURL分别以GETPOST方式请求HTTPS协议接口api

PHP如何通过CURL上传文件

php中 curl模拟post发送json并接收json(转)

PHP怎样处理HTTPS请求

如何向php服务器发送数据为json的post请求