I hope everyone still healthy…
So finally I got the coding done.
So I use both Apache (for sites who like to display my video will get blocked with wrong header others are all allowed) and am using PHP token and expiration time, so serve the video with PHP, chunk by chunk.
Found some codes on the web to serve mp4 with PHP, these codes were almost perfect, but found some bugs or something in there I didn’t like. I added a little bit more breath to it like this (I added the S count system in While, I hope this does not cause any troubles in the long run):
///working part of the code
if (file_exists($file)) {
$fp = @fopen($file, 'rb');
$size = filesize($file); // File size
$length = $size; // Content length
$start = 0; // Start byte
$end = $size - 1; // End byte
header('Content-type: video/'.$filetype.'');
//header("Accept-Ranges: 0-$length");
header("Accept-Ranges: bytes");
if (isset($_SERVER['HTTP_RANGE'])) {
$c_start = $start;
$c_end = $end;
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if (strpos($range, ',') !== false) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
if ($range == '-') {
$c_start = $size - substr($range, 1);
}else{
$range = explode('-', $range);
$c_start = $range[0];
$c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
}
$c_end = ($c_end > $end) ? $end : $c_end;
if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) {
header('HTTP/1.1 416 Requested Range Not Satisfiable');
header("Content-Range: bytes $start-$end/$size");
exit;
}
$start = $c_start;
$end = $c_end;
$length = $end - $start + 1;
fseek($fp, $start);
header('HTTP/1.1 206 Partial Content');
}
header("Content-Range: bytes $start-$end/$size");
header("Content-Length: ".$length);
$buffer = 1024 * 8;
$s=0;
while(!feof($fp) && ($p = ftell($fp)) <= $end) {
if ($p + $buffer > $end) {
$buffer = $end - $p + 1;
}
$s=$s+1;
//take a break start/my modification
echo fread($fp, $buffer);
if ($s >= 500) {
ob_clean();
ob_flush();
flush();
break;
//take a break
} else {
flush();
}
}
fclose($fp);
exit();
//file does not exists:
} else {
header("HTTP/1.1 404 Not Found");
exit;
}
or else the PHP will stay mostly alive(stuck in use) until file is completely loaded or almost loaded, this way it loads by small chunks and does free the PHP process immediately, also if you want to download the file you need to download all 50 pieces or something like that. (one PHP process per user).
I use session system for security and performance (one session one file principle). So if you do not have cookies you can not watch videos. You can watch one video at a time etc
Performance is everything, I like fast servers who doesn’t, right?
Anyways I tested this code on iPhone safari, Firefox, chrome. Seems to be working fine.
If anyone can give any suggestions how to improve/fix this any further would be great!
Wish you all well