4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
14 use Symfony\Component\HttpFoundation\File\File;
15 use Symfony\Component\HttpFoundation\File\Exception\FileException;
18 * BinaryFileResponse represents an HTTP response delivering a file.
20 * @author Niklas Fiekas <niklas.fiekas@tu-clausthal.de>
21 * @author stealth35 <stealth35-php@live.fr>
22 * @author Igor Wiedler <igor@wiedler.ch>
23 * @author Jordan Alliot <jordan.alliot@gmail.com>
24 * @author Sergey Linnik <linniksa@gmail.com>
26 class BinaryFileResponse extends Response
28 protected static $trustXSendfileTypeHeader = false;
36 protected $deleteFileAfterSend = false;
41 * @param \SplFileInfo|string $file The file to stream
42 * @param int $status The response status code
43 * @param array $headers An array of response headers
44 * @param bool $public Files are public by default
45 * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
46 * @param bool $autoEtag Whether the ETag header should be automatically set
47 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
49 public function __construct($file, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
51 parent::__construct(null, $status, $headers);
53 $this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
61 * @param \SplFileInfo|string $file The file to stream
62 * @param int $status The response status code
63 * @param array $headers An array of response headers
64 * @param bool $public Files are public by default
65 * @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
66 * @param bool $autoEtag Whether the ETag header should be automatically set
67 * @param bool $autoLastModified Whether the Last-Modified header should be automatically set
71 public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
73 return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
77 * Sets the file to stream.
79 * @param \SplFileInfo|string $file The file to stream
80 * @param string $contentDisposition
81 * @param bool $autoEtag
82 * @param bool $autoLastModified
86 * @throws FileException
88 public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
90 if (!$file instanceof File) {
91 if ($file instanceof \SplFileInfo) {
92 $file = new File($file->getPathname());
94 $file = new File((string) $file);
98 if (!$file->isReadable()) {
99 throw new FileException('File must be readable.');
105 $this->setAutoEtag();
108 if ($autoLastModified) {
109 $this->setAutoLastModified();
112 if ($contentDisposition) {
113 $this->setContentDisposition($contentDisposition);
122 * @return File The file to stream
124 public function getFile()
130 * Automatically sets the Last-Modified header according the file modification date.
132 public function setAutoLastModified()
134 $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
140 * Automatically sets the ETag header according to the checksum of the file.
142 public function setAutoEtag()
144 $this->setEtag(sha1_file($this->file->getPathname()));
150 * Sets the Content-Disposition header with the given filename.
152 * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
153 * @param string $filename Optionally use this filename instead of the real name of the file
154 * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
158 public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
160 if ($filename === '') {
161 $filename = $this->file->getFilename();
164 if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
165 $encoding = mb_detect_encoding($filename, null, true);
167 for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
168 $char = mb_substr($filename, $i, 1, $encoding);
170 if ('%' === $char || ord($char) < 32 || ord($char) > 126) {
171 $filenameFallback .= '_';
173 $filenameFallback .= $char;
178 $dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
179 $this->headers->set('Content-Disposition', $dispositionHeader);
187 public function prepare(Request $request)
189 $this->headers->set('Content-Length', $this->file->getSize());
191 if (!$this->headers->has('Accept-Ranges')) {
192 // Only accept ranges on safe HTTP methods
193 $this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none');
196 if (!$this->headers->has('Content-Type')) {
197 $this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
200 if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
201 $this->setProtocolVersion('1.1');
204 $this->ensureIEOverSSLCompatibility($request);
209 if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
210 // Use X-Sendfile, do not send any content.
211 $type = $request->headers->get('X-Sendfile-Type');
212 $path = $this->file->getRealPath();
213 // Fall back to scheme://path for stream wrapped locations.
214 if (false === $path) {
215 $path = $this->file->getPathname();
217 if (strtolower($type) === 'x-accel-redirect') {
218 // Do X-Accel-Mapping substitutions.
219 // @link http://wiki.nginx.org/X-accel#X-Accel-Redirect
220 foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
221 $mapping = explode('=', $mapping, 2);
223 if (2 === count($mapping)) {
224 $pathPrefix = trim($mapping[0]);
225 $location = trim($mapping[1]);
227 if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
228 $path = $location.substr($path, strlen($pathPrefix));
234 $this->headers->set($type, $path);
236 } elseif ($request->headers->has('Range')) {
237 // Process the range headers.
238 if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
239 $range = $request->headers->get('Range');
240 $fileSize = $this->file->getSize();
242 list($start, $end) = explode('-', substr($range, 6), 2) + array(0);
244 $end = ('' === $end) ? $fileSize - 1 : (int) $end;
247 $start = $fileSize - $end;
248 $end = $fileSize - 1;
250 $start = (int) $start;
253 if ($start <= $end) {
254 if ($start < 0 || $end > $fileSize - 1) {
255 $this->setStatusCode(416);
256 $this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
257 } elseif ($start !== 0 || $end !== $fileSize - 1) {
258 $this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
259 $this->offset = $start;
261 $this->setStatusCode(206);
262 $this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
263 $this->headers->set('Content-Length', $end - $start + 1);
272 private function hasValidIfRangeHeader($header)
274 if ($this->getEtag() === $header) {
278 if (null === $lastModified = $this->getLastModified()) {
282 return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
290 public function sendContent()
292 if (!$this->isSuccessful()) {
293 return parent::sendContent();
296 if (0 === $this->maxlen) {
300 $out = fopen('php://output', 'wb');
301 $file = fopen($this->file->getPathname(), 'rb');
303 stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
308 if ($this->deleteFileAfterSend) {
309 unlink($this->file->getPathname());
318 * @throws \LogicException when the content is not null
320 public function setContent($content)
322 if (null !== $content) {
323 throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
332 public function getContent()
338 * Trust X-Sendfile-Type header.
340 public static function trustXSendfileTypeHeader()
342 self::$trustXSendfileTypeHeader = true;
346 * If this is set to true, the file will be unlinked after the request is send
347 * Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
349 * @param bool $shouldDelete
353 public function deleteFileAfterSend($shouldDelete)
355 $this->deleteFileAfterSend = $shouldDelete;