-
-
Save icodebuster/d49da0258ab266acf929bb7d997e0b43 to your computer and use it in GitHub Desktop.
Laravel Response extend for inline displaying of images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Laravel\File; | |
/** | |
* Put this in laravels libraries dir and make sure to | |
* remove Response in /config/application.php | |
* This file will be autoloaded by default. | |
* | |
* @author Nico R <[email protected]> | |
*/ | |
class Response extends \Laravel\Response | |
{ | |
/** | |
* Create a response that will force a image to be displayed inline. | |
* | |
* @param string $path Path to the image | |
* @param string $name Filename | |
* @param int $lifetime Lifetime in browsers cache | |
* @return Response | |
*/ | |
public static function inline($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 static::make('', 304, $headers); | |
} | |
$headers = array_merge($headers, array( | |
'Content-Type' => File::mime(File::extension($path)), | |
'Content-Length' => $length, | |
)); | |
return static::make(File::get($path), 200, $headers); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add a route like this. | |
Route::get('images/(:any?)', function($image = null) | |
{ | |
$path = path('storage').'tempimg/' . $image; | |
if (file_exists($path)) { | |
return Response::inline($path); | |
} | |
return Response::error(404); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment