N
N
Narek2015-07-13 04:11:05
Zend Framework
Narek, 2015-07-13 04:11:05

How to configure image caching in PHP and ZF2?

Greetings!
The problem is the following:
you need to force the browser to cache the pictures that the server gives as follows:

$path = ".../data/images/test.jpg";
$imageContent = file_get_contents($path);

$response->setContent($imageContent);
$response->getHeaders()
     ->addHeaderLine('Content-Transfer-Encoding', 'binary')
     ->addHeaderLine('Content-Type', mime_content_type($path))
     ->addHeaderLine('Content-Length', mb_strlen($imageContent));

Request :
GET /file-system/preview/67.jpeg HTTP/1.1
Host: portal.dev
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
If-Modified-Since: Wed, 01 Jul 2015 11:36:42 GMT
If-None-Match: 53161d02e10e6793155b9707c8af4668
Cache-Control: max-age=0
Referer: http://portal.dev/file-system/preview/67.jpeg
Cookie: PHPSESSID=ba792bnrfcqlfp8ubut2smc1j0
Connection: keep-alive

Server response :
HTTP/1.1 200 OK
Date: Mon, 13 Jul 2015 01:38:00 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.11
Expires: Wed, 12 Aug 2015 01:38:00 GMT
Cache-Control: max-age=2592000, must-revalidate
Pragma: no-cache
Last-Modified: Wed, 01 Jul 2015 11:36:42 GMT
Accept-Ranges: bytes
Etag: 53161d02e10e6793155b9707c8af4668
Content-Transfer-Encoding: binary
Content-Length: 3369
Keep-Alive: timeout=5, max=95
Connection: Keep-Alive
Content-Type: image/jpeg

And when I return 304, the browser does not display the image.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jaxel, 2015-07-13
@jaxel

The easiest way to do this is through .htaaccess

<ifmodule mod_expires.c>
    <filesmatch ".(jpg|jpeg|gif|png|css|js|woff)$">
            ExpiresActive on
            ExpiresDefault "access plus 30 day"
        </filesmatch>
</ifmodule>

mod_expires must be installed and enabled

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question