file_get_contents is a bad idea . Reading a large list of images via file_get_contents killed my small server. I had to find another solution, and now it works perfectly and very quickly for me.
The key is to use readfile ($ sFileName) instead of file_get_contents. Symfony Stream Response can perform a callback function that will be executed upon sending ($ oResponse-> send ()). So this is a good place to use readfile ().
As a small benefit, I recorded a caching method.
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\StreamedResponse; class ImageController { public function indexAction(Request $oRequest, Response $oResponse) { // Get the filename from the request // eg $oRequest->get("imagename") $sFileName = "/images_directory/demoimage.jpg"; if( ! is_file($sFileName)){ $oResponse->setStatusCode(404); return $oResponse; } // Caching... $sLastModified = filemtime($sFileName); $sEtag = md5_file($sFileName); $sFileSize = filesize($sFileName); $aInfo = getimagesize($sFileName); if(in_array($sEtag, $oRequest->getETags()) || $oRequest->headers->get('If-Modified-Since') === gmdate("D, d MYH:i:s", $sLastModified)." GMT" ){ $oResponse->headers->set("Content-Type", $aInfo['mime']); $oResponse->headers->set("Last-Modified", gmdate("D, d MYH:i:s", $sLastModified)." GMT"); $oResponse->setETag($sEtag); $oResponse->setPublic(); $oResponse->setStatusCode(304); return $oResponse; } $oStreamResponse = new StreamedResponse(); $oStreamResponse->headers->set("Content-Type", $aInfo['mime']); $oStreamResponse->headers->set("Content-Length", $sFileSize); $oStreamResponse->headers->set("ETag", $sEtag); $oStreamResponse->headers->set("Last-Modified", gmdate("D, d MYH:i:s", $sLastModified)." GMT"); $oStreamResponse->setCallback(function() use ($sFileName) { readfile($sFileName); }); return $oStreamResponse; } }
Phil
source share