Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save aznoisib/00d72915b513c2e6b9a1f35df8427008 to your computer and use it in GitHub Desktop.
Save aznoisib/00d72915b513c2e6b9a1f35df8427008 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