I want to allow binary files with some kind of access control. Since the control is quite complex, I can’t just let Apache serve the files, I have to serve them via PHP using my Zend Framework 2 application. The action is as follows:
public function sendAction() { $filename = ; $size = filesize($filename); $response = $this->getResponse(); if($this->getRequest()->getHeaders()->has('Range')) { list($unit, $range) = explode('=', $this->getRequest()->getHeaders()->get('Range')->toString()); $ranges = explode(',', $range); $ranges = explode('-', $ranges[0]); $start = (int)$ranges[0]; $end = (int)(isset($ranges[1]) ? $ranges[1] : $size - 1); $length = $start - $end; $response->getHeaders()->addHeaders(array('Content-Type' => 'audio/mpeg', 'Accept-Ranges' => 'bytes', 'Content-Length' => $length - 1)); $response->setStatusCode(206); $f = fopen($filename, 'r'); if($start) fseek($f, $start); $out = ''; while($length) { $read = ($length > 8192) ? 8192 : $length; $length -= $read; $out .= fread($fp,$read); } fclose($f); $response->setContent($out); } else { $response ->setContent(file_get_contents($filename)) ->getHeaders()->addHeaders(array('Content-Type' => 'audio/mpeg', 'Accept-Ranges' => 'bytes')); } return $this->getResponse(); }
Good for one, I'm sure this is very inefficient, since files are always loaded into RAM entirely for this, before being serviced.
However, this does not work. When I try to access the file, I get the correct audio/mpeg player in Chrome, but then the browser cancels the requests and stops. I can’t play the sound at all.
I couldn’t find any clues on the Internet about how to correctly implement answer 206 in Zend 2, maybe someone can help me here.
source share