I'm tying to make a php script to sownload video from youtube and stream it at the same time and this is my code ..
ini_set('max_execution_time', 0);
ini_set('memory_limit', '512M');
$vid_id = $_GET['vidId'];
if (!file_exists('../cache_files/youtube/' . $vid_id . '.mp4')) {
$vid_info = file_get_contents('https://www.youtube.com/get_video_info?video_id=' . $vid_id);
parse_str($vid_info);
$Array = explode(',', $url_encoded_fmt_stream_map);
foreach ($Array as $item) {
parse_str($item);
$format = trim(substr($type, 0, strpos($type, ';')));
if ($format = 'video/mp4' && $quality == 'medium') {
download($url, $vid_id);
break;
} else {
echo $reason;
}
}
} else {
ob_clean();
flush();
readfile('../cache_files/youtube/' . $vid_id . '.mp4');
exit;
}
function download($infile, $outfile)
{
$chunksize = 100 * (1024 * 1024);
$parts = parse_url($infile);
$i_handle = fsockopen($parts['host'], 80, $errstr, $errcode, 5);
$o_handle = fopen('../cache_files/youtube/' . $outfile . '.mp4', 'wb');
if ($i_handle == false || $o_handle == false) {
return false;
}
if (!empty($parts['query'])) {
$parts['path'] .= '?' . $parts['query'];
}
$request = "GET {$parts['path']} HTTP/1.1\r\n";
$request .= "Host: {$parts['host']}\r\n";
$request .= "User-Agent: Mozilla/5.0\r\n";
$request .= "Keep-Alive: 115\r\n";
$request .= "Connection: keep-alive\r\n\r\n";
fwrite($i_handle, $request);
$headers = array();
while (!feof($i_handle)) {
$line = fgets($i_handle);
if ($line == "\r\n")
break;
$headers[] = $line;
}
$length = 0;
foreach ($headers as $header) {
if (stripos($header, 'Content-Length:') === 0) {
$length = (int) str_replace('Content-Length: ', '', $header);
break;
}
}
$cnt = 0;
while (!feof($i_handle)) {
$buf = '';
echo $buf = fread($i_handle, $chunksize);
$bytes = fwrite($o_handle, $buf);
if ($bytes == false) {
return false;
}
$cnt += $bytes;
if ($cnt >= $length)
break;
}
fclose($i_handle);
fclose($o_handle);
if (file_exists('../cache_files/youtube/' . $outfile . '.mp4')) {
if (!filesize('../cache_files/youtube/' . $outfile . '.mp4') > 1024) {
unlink('../cache_files/youtube/' . $outfile . '.mp4');
}
}
return $cnt;
}
i use it like this
<video controls autoplay>
<source src='http://127.0.0.1/youtube.video.grabber.php?vidId=BYi7Lc2aclY'>
</video>
the "youtube.video.grabber.php" file now should start downloading the file to my disk and stream it to the client at the same time and it works but i can't move the video to the forward or the backward so i need to add some headers to this code like partial content and some other headers and here's the problem after adding the headers to the code it stops and won't work again .. so i wanna know how to add those headers to the this code or if you have a better solution to download and stream the file at the same time with the ability to move the video to the backward or the forward i will be grateful if you told me how .. thanks and sorry about my bad english