Created
January 7, 2018 20:02
-
-
Save voskobovich/15ad5fc71e957bbe87d45cd88295f5b8 to your computer and use it in GitHub Desktop.
Video streamer from remote server by HTTP on PHP (Yii2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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