Skip to content

Instantly share code, notes, and snippets.

@voskobovich
Created January 7, 2018 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save voskobovich/15ad5fc71e957bbe87d45cd88295f5b8 to your computer and use it in GitHub Desktop.
Save voskobovich/15ad5fc71e957bbe87d45cd88295f5b8 to your computer and use it in GitHub Desktop.
Video streamer from remote server by HTTP on PHP (Yii2)
/**
* @param $url
*/
public function actionStreamVideoFromCdn($url)
{
$headersCollection = Yii::$app->request->getHeaders();
$responseHeaders = [];
$chInfo = curl_init();
curl_setopt($chInfo, CURLOPT_URL, $url);
curl_setopt($chInfo, CURLOPT_NOBODY, 1);
curl_setopt($chInfo, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($chInfo, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($chInfo, CURLOPT_AUTOREFERER, 1);
if (null !== $headersCollection->get('range')) {
[$param, $range] = explode('=', $headersCollection->get('range'));
curl_setopt($chInfo, CURLOPT_RANGE, $range);
}
curl_setopt(
$chInfo,
CURLOPT_HEADERFUNCTION,
function ($curl, $header) use (&$responseHeaders) {
$len = \strlen($header);
$header = \explode(':', $header, 2);
if (\count($header) < 2) { // ignore invalid headers
return $len;
}
$name = \strtolower(\trim($header[0]));
$responseHeaders[$name] = \trim($header[1]);
return $len;
}
);
curl_exec($chInfo);
curl_close($chInfo);
header('Accept-Ranges: bytes');
header('Content-Type: ' . $responseHeaders['content-type']);
header('Content-Length: ' . $responseHeaders['content-length']);
if (isset($responseHeaders['content-range'])) {
header('HTTP/1.1 206 Partial Content');
header('Content-Range: ' . $responseHeaders['content-range']);
}
$chStream = curl_init();
curl_setopt($chStream, CURLOPT_URL, $url);
curl_setopt($chStream, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($chStream, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($chStream, CURLOPT_AUTOREFERER, 1);
if (null !== $headersCollection->get('range')) {
[$param, $range] = explode('=', $headersCollection->get('range'));
curl_setopt($chStream, CURLOPT_RANGE, $range);
}
curl_exec($chStream);
curl_close($chStream);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment