What is the 304 state
The server should return this 304 status code if the client sends a conditional GET request and the request has been allowed, and the contents of the document (since the last visit or according to the requested condition) have not changed. The simple expression is that the client has executed the GET, but the file has not changed.
PHP dynamic Output Picture Why do you want to enter 304
How does the client know that the content is not updated? In fact, this is not the client, but your server things, we all know that the server can set caching mechanism, this function is to improve the speed of Web site access, when you send a GET request, the server will call from the cache you want to access the content, This time the server can determine whether the page has been updated, and if not updated then he will give you a 304 status code return.
Sometimes it is necessary to create a picture with PHP dynamically, such as thumbnails of multiple proportions
However, the image generated in PHP with the header head state is 200, can not be cached, which is obviously not appropriate.
How you can cache images generated by PHP. This feature only checks the headers to see if the image is up to date and sends 304 code, and if so, the browser will use the cached version instead of downloading the new one. Otherwise the new image output to browse.
PHP Dynamic output Picture HTTP header 304 code
<?php
Return the browser request header
Use built in Apache FTN when PHP built as module,
or query $_server when CGI
function Getrequestheaders ()
{
if (function_exists ("Apache_request_headers"))
{
if ($headers = Apache_request_headers ())
{
return $headers;
}
}
$headers = Array ();
Grab the if_modified_since header
if (Isset ($_server[' http_if_modified_since '))
{
$headers [' if-modified-since '] = $_server[' http_if_modified_since '];
}
return $headers;
}
Return the requested graphic file to the browser
Or a 304 code to use the cached browser copy
function Displaygraphicfile ($graphicFileName, $fileType = ' jpeg ')
{
$fileModTime = Filemtime ($graphicFileName);
Getting headers sent by the client.
$headers = Getrequestheaders ();
Checking If the client is validating he cache and if it is current.
if (Isset ($headers [' if-modified-since ']) &&
(Strtotime ($headers [' if-modified-since ']) = = $fileModTime))
{
Client ' s cache is current, so we just respond ' 304 not Modified '.
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s ', $fileModTime).
' GMT ', true, 304);
}
Else
{
Image not cached or cache outdated, we respond ' OK ' and output the image.
Header (' last-modified: '. Gmdate (' d, D M Y h:i:s ', $fileModTime).
' GMT ', true, 200);
Header (' content-type:image/'. $fileType);
Header (' content-transfer-encoding:binary ');
Header (' Content-length: ' FileSize ($graphicFileName));
ReadFile ($graphicFileName);
}
}
Example usage
Displaygraphicfile ("./images/image.png");
?>