Skip to content

Instantly share code, notes, and snippets.

@dj1020
Last active August 29, 2015 14:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dj1020/e8c603d2265f3d0ca9d1 to your computer and use it in GitHub Desktop.
Save dj1020/e8c603d2265f3d0ca9d1 to your computer and use it in GitHub Desktop.
Laravel Response extend for inline displaying of images
<?php
Response::macro('inlineImage', function($path, $name = null, $lifetime = 0)
{
if (is_null($name)) {
$name = basename($path);
}
$filetime = filemtime($path);
$etag = md5($filetime . $path);
$time = gmdate('r', $filetime);
$expires = gmdate('r', $filetime + $lifetime);
$length = filesize($path);
$headers = array(
'Content-Disposition' => 'inline; filename="' . $name . '"',
'Last-Modified' => $time,
'Cache-Control' => 'must-revalidate',
'Expires' => $expires,
'Pragma' => 'public',
'Etag' => $etag,
);
$headerTest1 = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $time;
$headerTest2 = isset($_SERVER['HTTP_IF_NONE_MATCH']) && str_replace('"', '', stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])) == $etag;
if ($headerTest1 || $headerTest2) { //image is cached by the browser, we dont need to send it again
return Response::make('', 304, $headers);
}
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $path);
$headers = array_merge($headers, array(
'Content-Type' => $mime,
'Content-Length' => $length,
));
return Response::make(File::get($path), 200, $headers);
});
@dj1020
Copy link
Author

dj1020 commented Mar 19, 2015

Thanks to https://gist.github.com/Sentences/3945396
have corrected the mime type issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment