0

I have video streaming working just fine in CakePHP. Since the videos are private to each user, I have a CakePHP controller serve up the files if the users are authenticated. I also notice that all requests sent to the server have a Cookie: CAKEPHP=<stuff> header in their request.

The problem is that when a user pauses, then plays the video or when the user seeks along the video, Chrome sends a Range request with a certain byte range for my server to deliver. The request gets cancelled immediately. It should be noted that this request has no Cookie: CAKEPHP=<stuff> header.

I believe the request is denied because there is no session cookie. How can I force chrome (and possibly other browsers) to send a session cookie?

My CakePHP Version is 2.4.1

EDIT:

view_media.ctp

<?php echo $this->Html->script(array('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', 'mediaelement-and-player'), array('inline' => false));
echo $this->Html->css(array('mediaelementplayer.min'), array('inline' => false));
?>
<video width="320" height="240"  controls preload="none">
<?php 
    if(isset($_SERVER['HTTP_USER_AGENT'])){
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent,'Chrome') !== false) {
            echo '<source src="/pages/get_media/264/webm" type="video/webm">';
        }
        if (strpos($agent,'Mozilla') !== false) {
            echo '<source src="/pages/get_media/264/mp4" type="video/mp4">';
        }
    }
?>
Your browser does not support HTML5.
</video>

(The view_media function in the Controller is blank)

Relevant section of PagesController

public function get_media($id, $type){
    $dbh = new PDO('mysql:host='.$dbhost;dbname=$dbname, $username, $password);
    //get media info
    $sth = $dbh->prepare("SELECT `owner`, `type` FROM media WHERE id=:id");
    $sth->bindParam(':id', $id);
    $sth->execute();
    $row = $sth->fetch();
    if($row['owner'] == $this->Auth->user('id')){
        if($row['type'] == 'png'){
            header("Content-type: image/png");
            echo  file_get_contents("/srv/Ads/Ad_".$id.".png");
        }else if($row['type'] == 'mp4'){
            if($type == "mp4"){
                header("Content-type: video/mp4");
                $filename = "/srv/Ads/Ad_".$id.".mp4";
            }else if($type == "webm"){
                header("Content-type: video/webm");
                $filename = "/srv/Ads/Ad_".$id.".webm";
            }else{
                die;
            }
            $this->send_video($filename);
        }
        die;
    }
}
//thanks to http://stackoverflow.com/questions/16732419/mp4-from-php-not-playing-in-html5-video-tag
private function send_video($path){
    if (file_exists($path)){
        $size=filesize($path);
        $fm=@fopen($path,'rb');
        if(!$fm) {
            // You can also redirect here
            header ("HTTP/1.0 404 Not Found");
            die;
        }
        $begin=0;
        $end=$size;
        if(isset($_SERVER['HTTP_RANGE'])) {
            if(preg_match('/bytes=\h*(\d+)-(\d*)[\D.*]?/i',   
            $_SERVER['HTTP_RANGE'],$matches)){
                $begin=intval($matches[0]);
                if(!empty($matches[1])) {
                    $end=intval($matches[1]);
                }
            }
        }
        if($begin>0||$end<$size)
            header('HTTP/1.0 206 Partial Content');
        else
            header('HTTP/1.0 200 OK');
        header('Accept-Ranges: bytes');
        header('Content-Length:'.($end-$begin));
        header("Content-Disposition: inline;");
        header("Content-Range: bytes $begin-$end/$size");
        header("Content-Transfer-Encoding: binary\n");
        header('Connection: close');
        $cur=$begin;
        fseek($fm,$begin,0);
        while(!feof($fm)&&$cur<$end&&(connection_status()==0)){
            echo fread($fm,min(1024*16,$end-$cur));
            $cur+=1024*16;
            usleep(1000);
        }
        die;
    }
}

(get_media has no view)

These are the requests. manage_media.js is blank for now, I will use it to load all media files one this video thing is working.

link

dudeofea
  • 330
  • 4
  • 21
  • I was just about to suggest some details for a new question :) The following would be helpful: OS/Browser version, headers of a successful as well as a problematic request, headers and contents of the responses for these requests, the PHP code that handles serving the files, and maybe also an HTML sample. btw, I just gave it a go with CakePHP 2.4.1 and Chrome 31.0.1650.57 m on Windows 7 x64, and it's working fine for me, the session cookie is being sent as expected. Have you tried it with a clean profile and other browsers? – ndm Nov 22 '13 at 22:52
  • I've added info. My Chrome version is also 31.0.1650.57m on Windows 8 – dudeofea Nov 25 '13 at 18:43
  • Couple of points: you don’t need to PHP to check the browser when printing the `` tag; just print them both and the browser will use the first appropriate one. And secondly, are you *really* creating a PDO instance and hard-coding queries in your controller actions?! – Martin Bean Nov 26 '13 at 16:11
  • what do you suggest instead? – dudeofea Nov 26 '13 at 17:43

1 Answers1

1

I think the request is actually made correctly, it's just the console not displaying it properly as the servers response is not correct. Try using a debug proxy like Charles to check the request.

Invalid response range

The response always serves starting from byte 0 and it uses the first byte position as the last byte position, both because the wrong indices are used on the regex matches. Index 0 contains the whole matched subject, ie the complete bytes=xyz string, and index 1 contains the first capture, ie the first byte position.

The actual captured values you are looking for are located at index 1 and 2.

$begin=intval($matches[1]);
if(!empty($matches[2])) {
    $end=intval($matches[2]);
}

Invalid content range

Also the Content-Range header is wrong, the last byte position must be end - 1 as the first byte starts at 0.

$last = $end - 1;
header("Content-Range: bytes $begin-$last/$size");

See also http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35

A byte-content-range-spec with a byte-range-resp-spec whose last- byte-pos value is less than its first-byte-pos value, or whose instance-length value is less than or equal to its last-byte-pos value, is invalid. The recipient of an invalid byte-content-range- spec MUST ignore it and any content transferred along with it.

[...]

Examples of byte-content-range-spec values, assuming that the entity contains a total of 1234 bytes:

. The first 500 bytes:
bytes 0-499/1234

. The second 500 bytes:
bytes 500-999/1234

. All except for the first 500 bytes:
bytes 500-1233/1234

. The last 500 bytes:
bytes 734-1233/1234

Use CakePHP instead

btw, is there a reason why you aren't using the CakePHP functionality for querying the database and serving files? You would save yourself a lot of trouble that way.

See http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse

Some (untested) example code:

public function get_media($id, $type)
{
    $media = $this->Media->findById($id, array('Media.owner', 'Media.type'));
    if($media['Media']['owner'] !== $this->Auth->user('id'))
    {
        throw new ForbiddenException();
    }

    $file = null;
    if($media['Media']['type'] == 'png')
    {
        $file = "/srv/Ads/Ad_".$id.".png";
    }
    else if($media['Media']['type'] == 'mp4')
    {
        if($type == "mp4")
        {
            $file = "/srv/Ads/Ad_".$id.".mp4";
        }
        else if($type == "webm")
        {
            $file = "/srv/Ads/Ad_".$id.".webm";
        }
    }

    $this->response->file($file, array('download' => true));
    return $this->response;
}
ndm
  • 59,784
  • 9
  • 71
  • 110