class BinaryFileResponse extends Response
BinaryFileResponse represents an HTTP response delivering a file.
HTTP_CONTINUE = 100; |
|
HTTP_SWITCHING_PROTOCOLS = 101; |
|
HTTP_PROCESSING = 102; // RFC2518 |
|
HTTP_OK = 200; |
|
HTTP_CREATED = 201; |
|
HTTP_ACCEPTED = 202; |
|
HTTP_NON_AUTHORITATIVE_INFORMATION = 203; |
|
HTTP_NO_CONTENT = 204; |
|
HTTP_RESET_CONTENT = 205; |
|
HTTP_PARTIAL_CONTENT = 206; |
|
HTTP_MULTI_STATUS = 207; // RFC4918 |
|
HTTP_ALREADY_REPORTED = 208; // RFC5842 |
|
HTTP_IM_USED = 226; // RFC3229 |
|
HTTP_MULTIPLE_CHOICES = 300; |
|
HTTP_MOVED_PERMANENTLY = 301; |
|
HTTP_FOUND = 302; |
|
HTTP_SEE_OTHER = 303; |
|
HTTP_NOT_MODIFIED = 304; |
|
HTTP_USE_PROXY = 305; |
|
HTTP_RESERVED = 306; |
|
HTTP_TEMPORARY_REDIRECT = 307; |
|
HTTP_PERMANENTLY_REDIRECT = 308; // RFC7238 |
|
HTTP_BAD_REQUEST = 400; |
|
HTTP_UNAUTHORIZED = 401; |
|
HTTP_PAYMENT_REQUIRED = 402; |
|
HTTP_FORBIDDEN = 403; |
|
HTTP_NOT_FOUND = 404; |
|
HTTP_METHOD_NOT_ALLOWED = 405; |
|
HTTP_NOT_ACCEPTABLE = 406; |
|
HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; |
|
HTTP_REQUEST_TIMEOUT = 408; |
|
HTTP_CONFLICT = 409; |
|
HTTP_GONE = 410; |
|
HTTP_LENGTH_REQUIRED = 411; |
|
HTTP_PRECONDITION_FAILED = 412; |
|
HTTP_REQUEST_ENTITY_TOO_LARGE = 413; |
|
HTTP_REQUEST_URI_TOO_LONG = 414; |
|
HTTP_UNSUPPORTED_MEDIA_TYPE = 415; |
|
HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; |
|
HTTP_EXPECTATION_FAILED = 417; |
|
HTTP_I_AM_A_TEAPOT = 418; // RFC2324 |
|
HTTP_MISDIRECTED_REQUEST = 421; // RFC7540 |
|
HTTP_UNPROCESSABLE_ENTITY = 422; // RFC4918 |
|
HTTP_LOCKED = 423; // RFC4918 |
|
HTTP_FAILED_DEPENDENCY = 424; // RFC4918 |
|
HTTP_RESERVED_FOR_WEBDAV_ADVANCED_COLLECTIONS_EXPIRED_PROPOSAL = 425; // RFC2817 |
|
HTTP_UPGRADE_REQUIRED = 426; // RFC2817 |
|
HTTP_PRECONDITION_REQUIRED = 428; // RFC6585 |
|
HTTP_TOO_MANY_REQUESTS = 429; // RFC6585 |
|
HTTP_REQUEST_HEADER_FIELDS_TOO_LARGE = 431; // RFC6585 |
|
HTTP_UNAVAILABLE_FOR_LEGAL_REASONS = 451; |
|
HTTP_INTERNAL_SERVER_ERROR = 500; |
|
HTTP_NOT_IMPLEMENTED = 501; |
|
HTTP_BAD_GATEWAY = 502; |
|
HTTP_SERVICE_UNAVAILABLE = 503; |
|
HTTP_GATEWAY_TIMEOUT = 504; |
|
HTTP_VERSION_NOT_SUPPORTED = 505; |
|
HTTP_VARIANT_ALSO_NEGOTIATES_EXPERIMENTAL = 506; // RFC2295 |
|
HTTP_INSUFFICIENT_STORAGE = 507; // RFC4918 |
|
HTTP_LOOP_DETECTED = 508; // RFC5842 |
|
HTTP_NOT_EXTENDED = 510; // RFC2774 |
|
HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 |
|
ResponseHeaderBag
|
$headers |
from Response | |
protected string
|
$content |
from Response | |
protected string
|
$version |
from Response | |
protected int
|
$statusCode |
from Response | |
protected string
|
$statusText |
from Response | |
protected string
|
$charset |
from Response | |
static array
|
$statusTexts |
Status codes translation table. | from Response |
static protected
|
$trustXSendfileTypeHeader |
||
protected File
|
$file |
||
protected
|
$offset |
||
protected
|
$maxlen |
||
protected
|
$deleteFileAfterSend |
public
|
|
__construct(SplFileInfo|string $file, $status = 200, array $headers = array(), bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
|
No description | |
public static
|
Response |
create(SplFileInfo|string $file = null, int $status = 200, array $headers = array(), bool $public = true, null|string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
|
No description | |
public
|
string |
__toString()
|
Returns the Response as an HTTP string. | from Response |
public
|
|
__clone()
|
Clones the current Response instance. | from Response |
public
|
$this |
prepare(Request $request)
|
Prepares the Response before it is sent to the client. | |
public
|
$this |
sendHeaders()
|
Sends HTTP headers. | from Response |
public
|
$this |
sendContent()
|
Sends the file. | |
public
|
$this |
send()
|
Sends HTTP headers and content. | from Response |
public
|
$this |
setContent(mixed $content)
|
Sets the response content. | |
public
|
string |
getContent()
|
Gets the current response content. | |
public
|
$this |
setProtocolVersion($version)
|
Sets the HTTP protocol version (1.0 or 1.1). | from Response |
public
|
|
getProtocolVersion()
|
Gets the HTTP protocol version. | from Response |
public
|
$this |
setStatusCode($code, $text = null)
|
Sets the response status code. | from Response |
public
|
|
getStatusCode()
|
Retrieves the status code for the current web response. | from Response |
public
|
$this |
setCharset($charset)
|
Sets the response charset. | from Response |
public
|
|
getCharset()
|
Retrieves the response charset. | from Response |
public
|
|
isCacheable()
|
Returns true if the response may safely be kept in a shared (surrogate) cache. | from Response |
public
|
|
isFresh()
|
Returns true if the response is "fresh". | from Response |
public
|
|
isValidateable()
|
Returns true if the response includes headers that can be used to validate the response with the origin server using a conditional GET request. | from Response |
public
|
$this |
setPrivate()
|
Marks the response as "private". | from Response |
public
|
$this |
setPublic()
|
Marks the response as "public". | from Response |
public
|
$this |
setImmutable($immutable = true)
|
Marks the response as "immutable". | from Response |
public
|
|
isImmutable()
|
Returns true if the response is marked as "immutable". | from Response |
public
|
|
mustRevalidate()
|
Returns true if the response must be revalidated by caches. | from Response |
public
|
|
getDate()
|
Returns the Date header as a DateTime instance. | from Response |
public
|
$this |
setDate(DateTimeInterface $date)
|
Sets the Date header. | from Response |
public
|
|
getAge()
|
Returns the age of the response in seconds. | from Response |
public
|
$this |
expire()
|
Marks the response stale by setting the Age header to be equal to the maximum age of the response. | from Response |
public
|
|
getExpires()
|
Returns the value of the Expires header as a DateTime instance. | from Response |
public
|
$this |
setExpires(DateTimeInterface $date = null)
|
Sets the Expires HTTP header with a DateTime instance. | from Response |
public
|
|
getMaxAge()
|
Returns the number of seconds after the time specified in the response's Date header when the response should no longer be considered fresh. | from Response |
public
|
$this |
setMaxAge($value)
|
Sets the number of seconds after which the response should no longer be considered fresh. | from Response |
public
|
$this |
setSharedMaxAge($value)
|
Sets the number of seconds after which the response should no longer be considered fresh by shared caches. | from Response |
public
|
|
getTtl()
|
Returns the response's time-to-live in seconds. | from Response |
public
|
$this |
setTtl($seconds)
|
Sets the response's time-to-live for shared caches in seconds. | from Response |
public
|
$this |
setClientTtl($seconds)
|
Sets the response's time-to-live for private/client caches in seconds. | from Response |
public
|
|
getLastModified()
|
Returns the Last-Modified HTTP header as a DateTime instance. | from Response |
public
|
$this |
setLastModified(DateTimeInterface $date = null)
|
Sets the Last-Modified HTTP header with a DateTime instance. | from Response |
public
|
|
getEtag()
|
Returns the literal value of the ETag HTTP header. | from Response |
public
|
$this |
setEtag(string|null $etag = null, bool $weak = false)
|
Sets the ETag value. | from Response |
public
|
$this |
setCache($options)
|
Sets the response's cache headers (validation and/or expiration). | from Response |
public
|
$this |
setNotModified()
|
Modifies the response so that it conforms to the rules defined for a 304 status code. | from Response |
public
|
|
hasVary()
|
Returns true if the response includes a Vary header. | from Response |
public
|
|
getVary()
|
Returns an array of header names given in the Vary header. | from Response |
public
|
$this |
setVary(string|array $headers, bool $replace = true)
|
Sets the Vary header. | from Response |
public
|
bool |
isNotModified(Request $request)
|
Determines if the Response validators (ETag, Last-Modified) match a conditional value specified in the Request. | from Response |
public
|
|
isInvalid()
|
Is response invalid? | from Response |
public
|
|
isInformational()
|
Is response informative? | from Response |
public
|
|
isSuccessful()
|
Is response successful? | from Response |
public
|
|
isRedirection()
|
Is the response a redirect? | from Response |
public
|
|
isClientError()
|
Is there a client error? | from Response |
public
|
|
isServerError()
|
Was there a server side error? | from Response |
public
|
|
isOk()
|
Is the response OK? | from Response |
public
|
|
isForbidden()
|
Is the response forbidden? | from Response |
public
|
|
isNotFound()
|
Is the response a not found error? | from Response |
public
|
|
isRedirect($location = null)
|
Is the response a redirect of some form? | from Response |
public
|
|
isEmpty()
|
Is the response empty? | from Response |
public static
|
|
closeOutputBuffers($targetLevel, $flush)
|
Cleans or flushes output buffers up to target level. | from Response |
protected
|
|
ensureIEOverSSLCompatibility(Request $request)
|
Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9. | from Response |
public
|
$this |
setFile(SplFileInfo|string $file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
|
Sets the file to stream. | |
public
|
File |
getFile()
|
Gets the file. | |
public
|
|
setAutoLastModified()
|
Automatically sets the Last-Modified header according the file modification date. | |
public
|
|
setAutoEtag()
|
Automatically sets the ETag header according to the checksum of the file. | |
public
|
$this |
setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')
|
Sets the Content-Disposition header with the given filename. | |
public static
|
|
trustXSendfileTypeHeader()
|
Trust X-Sendfile-Type header. | |
public
|
$this |
deleteFileAfterSend(bool $shouldDelete = true)
|
If this is set to true, the file will be unlinked after the request is send Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used. |
__construct()public __construct(SplFileInfo|string $file, $status = 200, array $headers = array(), bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
SplFileInfo|string |
$file |
The file to stream |
$status |
||
array |
$headers |
|
bool |
$public |
Files are public by default |
string |
$contentDisposition |
The type of Content-Disposition to set automatically with the filename |
bool |
$autoEtag |
Whether the ETag header should be automatically set |
bool |
$autoLastModified |
Whether the Last-Modified header should be automatically set |
create()public static Response create(SplFileInfo|string $file = null, int $status = 200, array $headers = array(), bool $public = true, null|string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
SplFileInfo|string |
$file |
The file to stream |
int |
$status |
The response status code |
array |
$headers |
An array of response headers |
bool |
$public |
Files are public by default |
null|string |
$contentDisposition |
The type of Content-Disposition to set automatically with the filename |
bool |
$autoEtag |
Whether the ETag header should be automatically set |
bool |
$autoLastModified |
Whether the Last-Modified header should be automatically set |
Response |
__toString()public string __toString()
Returns the Response as an HTTP string.
The string representation of the Response is the same as the one that will be sent to the client only if the prepare() method has been called before.
string |
The Response as an HTTP string |
| prepare() |
__clone()public __clone()
Clones the current Response instance.
Prepares the Response before it is sent to the client.
This method tweaks the Response to ensure that it is compliant with RFC 2616. Most of the changes are based on the Request that is "associated" with this Response.
Request |
$request |
$this |
sendHeaders()public $this sendHeaders()
Sends HTTP headers.
$this |
sendContent()public $this sendContent()
Sends the file.
{@inheritdoc}
$this |
send()public $this send()
Sends HTTP headers and content.
$this |
setContent()public $this setContent(mixed $content)
Sets the response content.
Valid types are strings, numbers, null, and objects that implement a __toString() method.
mixed |
$content |
Content that can be cast to string |
$this |
| UnexpectedValueException |
getContent()public string getContent()
Gets the current response content.
string |
Content |
setProtocolVersion()public $this setProtocolVersion($version)
Sets the HTTP protocol version (1.0 or 1.1).
$version |
$this |
getProtocolVersion()public getProtocolVersion()
Gets the HTTP protocol version.
setStatusCode()public $this setStatusCode($code, $text = null)
Sets the response status code.
If the status text is null it will be automatically populated for the known status codes and left empty otherwise.
$code |
||
$text |
$this |
| InvalidArgumentException | When the HTTP status code is not valid |
getStatusCode()public getStatusCode()
Retrieves the status code for the current web response.
setCharset()public $this setCharset($charset)
Sets the response charset.
$charset |
$this |
getCharset()public getCharset()
Retrieves the response charset.
isCacheable()public isCacheable()
Returns true if the response may safely be kept in a shared (surrogate) cache.
Responses marked "private" with an explicit Cache-Control directive are considered uncacheable.
Responses with neither a freshness lifetime (Expires, max-age) nor cache validator (Last-Modified, ETag) are considered uncacheable because there is no way to tell when or how to remove them from the cache.
Note that RFC 7231 and RFC 7234 possibly allow for a more permissive implementation, for example "status codes that are defined as cacheable by default [...] can be reused by a cache with heuristic expiration unless otherwise indicated" (https://tools.ietf.org/html/rfc7231#section-6.1)
isFresh()public isFresh()
Returns true if the response is "fresh".
Fresh responses may be served from cache without any interaction with the origin. A response is considered fresh when it includes a Cache-Control/max-age indicator or Expires header and the calculated age is less than the freshness lifetime.
isValidateable()public isValidateable()
Returns true if the response includes headers that can be used to validate the response with the origin server using a conditional GET request.
setPrivate()public $this setPrivate()
Marks the response as "private".
It makes the response ineligible for serving other clients.
$this |
setPublic()public $this setPublic()
Marks the response as "public".
It makes the response eligible for serving other clients.
$this |
setImmutable()public $this setImmutable($immutable = true)
Marks the response as "immutable".
$immutable |
$this |
isImmutable()public isImmutable()
Returns true if the response is marked as "immutable".
mustRevalidate()public mustRevalidate()
Returns true if the response must be revalidated by caches.
This method indicates that the response must not be served stale by a cache in any circumstance without first revalidating with the origin. When present, the TTL of the response should not be overridden to be greater than the value provided by the origin.
getDate()public getDate()
Returns the Date header as a DateTime instance.
| RuntimeException | When the header is not parseable |
setDate()public $this setDate(DateTimeInterface $date)
getAge()public getAge()
Returns the age of the response in seconds.
expire()public $this expire()
Marks the response stale by setting the Age header to be equal to the maximum age of the response.
$this |
getExpires()public getExpires()
Returns the value of the Expires header as a DateTime instance.
setExpires()public $this setExpires(DateTimeInterface $date = null)
Sets the Expires HTTP header with a DateTime instance.
Passing null as value will remove the header.
DateTimeInterface |
$date |
$this |
getMaxAge()public getMaxAge()
Returns the number of seconds after the time specified in the response's Date header when the response should no longer be considered fresh.
First, it checks for a s-maxage directive, then a max-age directive, and then it falls back on an expires header. It returns null when no maximum age can be established.
setMaxAge()public $this setMaxAge($value)
Sets the number of seconds after which the response should no longer be considered fresh.
This methods sets the Cache-Control max-age directive.
$value |
$this |
setSharedMaxAge()public $this setSharedMaxAge($value)
Sets the number of seconds after which the response should no longer be considered fresh by shared caches.
This methods sets the Cache-Control s-maxage directive.
$value |
$this |
getTtl()public getTtl()
Returns the response's time-to-live in seconds.
It returns null when no freshness information is present in the response.
When the responses TTL is <= 0, the response may not be served from cache without first revalidating with the origin.
setTtl()public $this setTtl($seconds)
Sets the response's time-to-live for shared caches in seconds.
This method adjusts the Cache-Control/s-maxage directive.
$seconds |
$this |
setClientTtl()public $this setClientTtl($seconds)
Sets the response's time-to-live for private/client caches in seconds.
This method adjusts the Cache-Control/max-age directive.
$seconds |
$this |
getLastModified()public getLastModified()
Returns the Last-Modified HTTP header as a DateTime instance.
| RuntimeException | When the HTTP header is not parseable |
setLastModified()public $this setLastModified(DateTimeInterface $date = null)
Sets the Last-Modified HTTP header with a DateTime instance.
Passing null as value will remove the header.
DateTimeInterface |
$date |
$this |
getEtag()public getEtag()
Returns the literal value of the ETag HTTP header.
setEtag()public $this setEtag(string|null $etag = null, bool $weak = false)
Sets the ETag value.
string|null |
$etag |
The ETag unique identifier or null to remove the header |
bool |
$weak |
Whether you want a weak ETag or not |
$this |
setCache()public $this setCache($options)
Sets the response's cache headers (validation and/or expiration).
Available options are: etag, last_modified, max_age, s_maxage, private, public and immutable.
$options |
$this |
| InvalidArgumentException |
setNotModified()public $this setNotModified()
Modifies the response so that it conforms to the rules defined for a 304 status code.
This sets the status, removes the body, and discards any headers that MUST NOT be included in 304 responses.
$this |
| http://tools.ietf.org/html/rfc2616#section-10.3.5 |
hasVary()public hasVary()
Returns true if the response includes a Vary header.
getVary()public getVary()
Returns an array of header names given in the Vary header.
setVary()public $this setVary(string|array $headers, bool $replace = true)
Sets the Vary header.
string|array |
$headers |
|
bool |
$replace |
Whether to replace the actual value or not (true by default) |
$this |
Determines if the Response validators (ETag, Last-Modified) match a conditional value specified in the Request.
If the Response is not modified, it sets the status code to 304 and removes the actual content by calling the setNotModified() method.
Request |
$request |
bool |
true if the Response validators match the Request, false otherwise |
isInvalid()public isInvalid()
Is response invalid?
| http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html |
isInformational()public isInformational()
Is response informative?
isSuccessful()public isSuccessful()
Is response successful?
isRedirection()public isRedirection()
Is the response a redirect?
isClientError()public isClientError()
Is there a client error?
isServerError()public isServerError()
Was there a server side error?
isOk()public isOk()
Is the response OK?
isForbidden()public isForbidden()
Is the response forbidden?
isNotFound()public isNotFound()
Is the response a not found error?
isRedirect()public isRedirect($location = null)
Is the response a redirect of some form?
$location |
isEmpty()public isEmpty()
Is the response empty?
closeOutputBuffers()public static closeOutputBuffers($targetLevel, $flush)
Cleans or flushes output buffers up to target level.
Resulting level can be greater than target level if a non-removable buffer has been encountered.
$targetLevel |
||
$flush |
ensureIEOverSSLCompatibility()protected ensureIEOverSSLCompatibility(Request $request)
Checks if we need to remove Cache-Control for SSL encrypted downloads when using IE < 9.
Request |
$request |
| http://support.microsoft.com/kb/323308 |
setFile()public $this setFile(SplFileInfo|string $file, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
Sets the file to stream.
SplFileInfo|string |
$file |
The file to stream |
string |
$contentDisposition |
|
bool |
$autoEtag |
|
bool |
$autoLastModified |
$this |
| FileException |
setAutoLastModified()public setAutoLastModified()
Automatically sets the Last-Modified header according the file modification date.
setAutoEtag()public setAutoEtag()
Automatically sets the ETag header according to the checksum of the file.
setContentDisposition()public $this setContentDisposition(string $disposition, string $filename = '', string $filenameFallback = '')
Sets the Content-Disposition header with the given filename.
string |
$disposition |
ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT |
string |
$filename |
Optionally use this UTF-8 encoded filename instead of the real name of the file |
string |
$filenameFallback |
A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename |
$this |
trustXSendfileTypeHeader()public static trustXSendfileTypeHeader()
Trust X-Sendfile-Type header.
deleteFileAfterSend()public $this deleteFileAfterSend(bool $shouldDelete = true)
If this is set to true, the file will be unlinked after the request is send Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
bool |
$shouldDelete |
$this |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace App\Khan\Component\HttpFoundation;
use App\Khan\Component\HttpFoundation\File\File;
use App\Khan\Component\HttpFoundation\File\Exception\FileException;
/**
* BinaryFileResponse represents an HTTP response delivering a file.
*
* @author Niklas Fiekas <niklas.fiekas@tu-clausthal.de>
* @author stealth35 <stealth35-php@live.fr>
* @author Igor Wiedler <igor@wiedler.ch>
* @author Jordan Alliot <jordan.alliot@gmail.com>
* @author Sergey Linnik <linniksa@gmail.com>
*/
class BinaryFileResponse extends Response
{
protected static $trustXSendfileTypeHeader = false;
/**
* @var File
*/
protected $file;
protected $offset;
protected $maxlen;
protected $deleteFileAfterSend = false;
/**
* @param \SplFileInfo|string $file The file to stream
* @param int $status The response status code
* @param array $headers An array of response headers
* @param bool $public Files are public by default
* @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
* @param bool $autoEtag Whether the ETag header should be automatically set
* @param bool $autoLastModified Whether the Last-Modified header should be automatically set
*/
public function __construct($file, int $status = 200, array $headers = array(), bool $public = true, string $contentDisposition = null, bool $autoEtag = false, bool $autoLastModified = true)
{
parent::__construct(null, $status, $headers);
$this->setFile($file, $contentDisposition, $autoEtag, $autoLastModified);
if ($public) {
$this->setPublic();
}
}
/**
* @param \SplFileInfo|string $file The file to stream
* @param int $status The response status code
* @param array $headers An array of response headers
* @param bool $public Files are public by default
* @param null|string $contentDisposition The type of Content-Disposition to set automatically with the filename
* @param bool $autoEtag Whether the ETag header should be automatically set
* @param bool $autoLastModified Whether the Last-Modified header should be automatically set
*
* @return static
*/
public static function create($file = null, $status = 200, $headers = array(), $public = true, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
{
return new static($file, $status, $headers, $public, $contentDisposition, $autoEtag, $autoLastModified);
}
/**
* Sets the file to stream.
*
* @param \SplFileInfo|string $file The file to stream
* @param string $contentDisposition
* @param bool $autoEtag
* @param bool $autoLastModified
*
* @return $this
*
* @throws FileException
*/
public function setFile($file, $contentDisposition = null, $autoEtag = false, $autoLastModified = true)
{
if (!$file instanceof File) {
if ($file instanceof \SplFileInfo) {
$file = new File($file->getPathname());
} else {
$file = new File((string) $file);
}
}
if (!$file->isReadable()) {
throw new FileException('File must be readable.');
}
$this->file = $file;
if ($autoEtag) {
$this->setAutoEtag();
}
if ($autoLastModified) {
$this->setAutoLastModified();
}
if ($contentDisposition) {
$this->setContentDisposition($contentDisposition);
}
return $this;
}
/**
* Gets the file.
*
* @return File The file to stream
*/
public function getFile()
{
return $this->file;
}
/**
* Automatically sets the Last-Modified header according the file modification date.
*/
public function setAutoLastModified()
{
$this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));
return $this;
}
/**
* Automatically sets the ETag header according to the checksum of the file.
*/
public function setAutoEtag()
{
$this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));
return $this;
}
/**
* Sets the Content-Disposition header with the given filename.
*
* @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
* @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file
* @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename
*
* @return $this
*/
public function setContentDisposition($disposition, $filename = '', $filenameFallback = '')
{
if ('' === $filename) {
$filename = $this->file->getFilename();
}
if ('' === $filenameFallback && (!preg_match('/^[\x20-\x7e]*$/', $filename) || false !== strpos($filename, '%'))) {
$encoding = mb_detect_encoding($filename, null, true) ?: '8bit';
for ($i = 0, $filenameLength = mb_strlen($filename, $encoding); $i < $filenameLength; ++$i) {
$char = mb_substr($filename, $i, 1, $encoding);
if ('%' === $char || ord($char) < 32 || ord($char) > 126) {
$filenameFallback .= '_';
} else {
$filenameFallback .= $char;
}
}
}
$dispositionHeader = $this->headers->makeDisposition($disposition, $filename, $filenameFallback);
$this->headers->set('Content-Disposition', $dispositionHeader);
return $this;
}
/**
* {@inheritdoc}
*/
public function prepare(Request $request)
{
if (!$this->headers->has('Content-Type')) {
$this->headers->set('Content-Type', $this->file->getMimeType() ?: 'application/octet-stream');
}
if ('HTTP/1.0' !== $request->server->get('SERVER_PROTOCOL')) {
$this->setProtocolVersion('1.1');
}
$this->ensureIEOverSSLCompatibility($request);
$this->offset = 0;
$this->maxlen = -1;
if (false === $fileSize = $this->file->getSize()) {
return $this;
}
$this->headers->set('Content-Length', $fileSize);
if (!$this->headers->has('Accept-Ranges')) {
// Only accept ranges on safe HTTP methods
$this->headers->set('Accept-Ranges', $request->isMethodSafe(false) ? 'bytes' : 'none');
}
if (self::$trustXSendfileTypeHeader && $request->headers->has('X-Sendfile-Type')) {
// Use X-Sendfile, do not send any content.
$type = $request->headers->get('X-Sendfile-Type');
$path = $this->file->getRealPath();
// Fall back to scheme://path for stream wrapped locations.
if (false === $path) {
$path = $this->file->getPathname();
}
if ('x-accel-redirect' === strtolower($type)) {
// Do X-Accel-Mapping substitutions.
// @link http://wiki.nginx.org/X-accel#X-Accel-Redirect
foreach (explode(',', $request->headers->get('X-Accel-Mapping', '')) as $mapping) {
$mapping = explode('=', $mapping, 2);
if (2 === count($mapping)) {
$pathPrefix = trim($mapping[0]);
$location = trim($mapping[1]);
if (substr($path, 0, strlen($pathPrefix)) === $pathPrefix) {
$path = $location.substr($path, strlen($pathPrefix));
break;
}
}
}
}
$this->headers->set($type, $path);
$this->maxlen = 0;
} elseif ($request->headers->has('Range')) {
// Process the range headers.
if (!$request->headers->has('If-Range') || $this->hasValidIfRangeHeader($request->headers->get('If-Range'))) {
$range = $request->headers->get('Range');
list($start, $end) = explode('-', substr($range, 6), 2) + array(0);
$end = ('' === $end) ? $fileSize - 1 : (int) $end;
if ('' === $start) {
$start = $fileSize - $end;
$end = $fileSize - 1;
} else {
$start = (int) $start;
}
if ($start <= $end) {
if ($start < 0 || $end > $fileSize - 1) {
$this->setStatusCode(416);
$this->headers->set('Content-Range', sprintf('bytes */%s', $fileSize));
} elseif (0 !== $start || $end !== $fileSize - 1) {
$this->maxlen = $end < $fileSize ? $end - $start + 1 : -1;
$this->offset = $start;
$this->setStatusCode(206);
$this->headers->set('Content-Range', sprintf('bytes %s-%s/%s', $start, $end, $fileSize));
$this->headers->set('Content-Length', $end - $start + 1);
}
}
}
}
return $this;
}
private function hasValidIfRangeHeader($header)
{
if ($this->getEtag() === $header) {
return true;
}
if (null === $lastModified = $this->getLastModified()) {
return false;
}
return $lastModified->format('D, d M Y H:i:s').' GMT' === $header;
}
/**
* Sends the file.
*
* {@inheritdoc}
*/
public function sendContent()
{
if (!$this->isSuccessful()) {
return parent::sendContent();
}
if (0 === $this->maxlen) {
return $this;
}
$out = fopen('php://output', 'wb');
$file = fopen($this->file->getPathname(), 'rb');
stream_copy_to_stream($file, $out, $this->maxlen, $this->offset);
fclose($out);
fclose($file);
if ($this->deleteFileAfterSend) {
unlink($this->file->getPathname());
}
return $this;
}
/**
* {@inheritdoc}
*
* @throws \LogicException when the content is not null
*/
public function setContent($content)
{
if (null !== $content) {
throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.');
}
}
/**
* {@inheritdoc}
*
* @return false
*/
public function getContent()
{
return false;
}
/**
* Trust X-Sendfile-Type header.
*/
public static function trustXSendfileTypeHeader()
{
self::$trustXSendfileTypeHeader = true;
}
/**
* If this is set to true, the file will be unlinked after the request is send
* Note: If the X-Sendfile header is used, the deleteFileAfterSend setting will not be used.
*
* @param bool $shouldDelete
*
* @return $this
*/
public function deleteFileAfterSend($shouldDelete = true)
{
$this->deleteFileAfterSend = $shouldDelete;
return $this;
}
}