Set etag header php

Setting HTTP Cache Headers with PHP

If you are just taking modern browsers into consideration, you need to set only «Cache-Control» and «ETag» headers. «Expires» and «Last-Modified» headers belong to an older HTTP specification and you can leave them out.

This tutorial will discuss how you can set «Cache-Control» and «ETag» headers through PHP.

For an understanding about HTTP caching in general, you can refer HTTP Cache Headers Explained and Practical Examples of Cache Headers.

Setting «Cache-Control» Header

Setting the «Cache-Control» header is direct. Just use the required directives for «Cache-Control» and send the header through the header function.

header('Cache-Control: max-age=86400');

Please note that you must use this function before any output from the script is emitted.

Setting «ETag» Header

Since the ETag header should be unique for a unique content, it requires a little logic. This tutorial dicusses one method based on timestamps through which you can create ETags — however this is just for example and you can use your own methods to create ETags. ETags based on a hash of the content are also popular.

2 timestamps can be related with a PHP script :

  • Generally PHP scripts send out dynamic content — for example some content from the database. That content usually has a last modified timestamp, which is also stored in the database.
  • Another timestamp is associated with the code contained in the PHP script — basically the timestamp when the PHP file was last modified.
Читайте также:  Заполнить двумерный массив случайными числами java

As an example, see the below 2 codes. The first one is the content of a PHP file at some time. The second one is the content of the same PHP file, but after some time (someone made a modification to the code).

The main content that the user sees is same for both, but the content of the PHP files are different (an extra script tag). So while creating ETags based on last modification timestamp, we will have to consider this also.

So we set the ETag as the concatatenation of the last modification timestamp of the main content (that user sees) AND the last modification timestamp of the PHP file (in the server filesystem). If any of these timestamps change, the ETag is changed.

Last modification timestamp of the PHP file in the server file system can be retrieved through the filemtime function.

PHP Codes to Set Cache Headers

 content is the same as browser cache // So send a 304 Not Modified response header and exit if($_SERVER['HTTP_IF_NONE_MATCH'] == $etag) < header('HTTP/1.1 304 Not Modified', true, 304); exit(); >> // Rest of the code in the PHP script ?> 

Источник

создание php eTag с использованием php

Этот PHP-код генерирует eTag для xml файла. Проблема заключается в обновлении eTag только при обновлении/изменении файла. Мне нужно, чтобы etag обновлялся, когда динамические результаты также обновляются. любая идея, как это можно сделать?

//get the last-modified-date of this very file $lastModified=filemtime(__FILE__); //get a unique hash of this file (etag) $etagFile = md5_file(__FILE__); //get the HTTP_IF_MODIFIED_SINCE header if set $ifModifiedSince=(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false); //get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash) $etagHeader=(isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false); //set last-modified header header("Last-Modified: ".gmdate("D, d M Y H:i:s", $lastModified)." GMT"); //set etag-header header("Etag: $etagFile"); //make sure caching is turned on //check if page has changed. If not, send 304 and exit if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])==$lastModified || $etagHeader == $etagFile) < header("HTTP/1.1 304 Not Modified"); exit; >

Получите уникальный файл динамического содержимого вместо файла и установите его как eTag . Например, $etagFile = md5( $your_output );

Установите уникальное значение, обозначающее ваши последние обновления. Это может быть простая последняя обновленная отметка времени ваших данных, но она немного уязвима, если в течение одной секунды может быть несколько изменений, и в этом случае вы добавляете идентификатор этого последнего содержимого. Что-то вроде псевдокода md5(md5file.max(mtimefile,mtimedata).identifierlastupdatedrecord);

не могли бы вы подробнее остановиться на этом, пожалуйста? как бы получить уникальный хэш динамического контента? @bystwn22 bystwn22

Источник

How to use etags in a PHP file?

Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:, 9 Note that this basically only work if the PHP file doesn’t include any other files. As updating other files, won’t change the ETag. – vallentin May 8 ’16 at 0:07 ,How do you implemented etags inside a PHP file? What do I upload to the server and what do I insert into my PHP file?,Connect and share knowledge within a single location that is structured and easy to search.

Create / edit your .htaccess file and add the following:

Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:

Answer by Oaklyn McGuire

Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:,Create / edit your .htaccess file and add the following:,How do you implemented etags inside a PHP file? What do I upload to the server and what do I insert into my PHP file?

Create / edit your .htaccess file and add the following:

Either place the following inside a function or put it at the top of the PHP file that you need etags to work on:

Answer by Regina Burns

Use this only when the web pages of a site directly map to corresponding PHP files.,This code snippet checks if a page has been modified since it was last displayed. If so, it sends a “304 not modified” header and exits, otherwise the content is rendered. Prepend this snippet on top of every PHP file you want to apply this intelligent caching-mechanism. Especially useful if you (have to) serve static content via php and want it to be cached like ordinary HTML or CSS.,i’ve added your code to the very top of my pages and tested my pages at http://web-sniffer.net, Rule Permalink to comment# February 10, 2012 So any one can make this thing to work? it seems interesting. Thank you Reply

This code snippet checks if a page has been modified since it was last displayed. If so, it sends a “304 not modified” header and exits, otherwise the content is rendered. Prepend this snippet on top of every PHP file you want to apply this intelligent caching-mechanism. Especially useful if you (have to) serve static content via php and want it to be cached like ordinary HTML or CSS.

 //your normal code echo "This page was last modified: ".date("d.m.Y H:i:s",time()); ?>

Answer by Mavis Meza

PHP includes a short echo tag and ) to maximise compatibility. ,Example #1 PHP Opening and Closing Tags, If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.

PHP tags

When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

PHP tags

When PHP parses a file, it looks for opening and closing tags, which are which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.

Answer by Miller Stephenson

Please note that you must use this function before any output from the script is emitted.,Last modification timestamp of the PHP file in the server file system can be retrieved through the filemtime function.,Setting the «Cache-Control» header is direct. Just use the required directives for «Cache-Control» and send the header through the header function.,Generally PHP scripts send out dynamic content — for example some content from the database. That content usually has a last modified timestamp, which is also stored in the database.

Setting the «Cache-Control» header is direct. Just use the required directives for «Cache-Control» and send the header through the header function.

header('Cache-Control: max-age=86400');

As an example, see the below 2 codes. The first one is the content of a PHP file at some time. The second one is the content of the same PHP file, but after some time (someone made a modification to the code).

PHP Codes to Set Cache Headers

 content is the same as browser cache // So send a 304 Not Modified response header and exit if($_SERVER['HTTP_IF_NONE_MATCH'] == $etag) < header('HTTP/1.1 304 Not Modified', true, 304); exit(); >> // Rest of the code in the PHP script ?> 

Answer by Kendrick Spencer

Another typical use of the ETag header is to cache resources that are unchanged. If a user visits a given URL again (that has an ETag set), and it is stale (too old to be considered usable), the client will send the value of its ETag along in an If-None-Match header field: , For example, when editing a wiki, the current wiki content may be hashed and put into an Etag header in the response: , With the help of the ETag and the If-Match headers, you can detect mid-air edit collisions. , When saving changes to a wiki page (posting data), the POST request will contain the If-Match header containing the ETag values to check freshness against.

Answer by Idris Rhodes

4 Tracking using ETags,2 Strong and weak validation,3.1 Mismatched ETag detection,3 Typical usage 3.1 Mismatched ETag detection

RFC-7232 explicitly states that ETags should be content-coding aware, e.g.

ETag: "123-a" – for no Content-Encoding ETag: "123-b" – for Content-Encoding: gzip 

The ETag mechanism supports both strong validation and weak validation. They are distinguished by the presence of an initial «W/» in the ETag identifier, as:

"123456789" – A strong ETag validator W/"123456789" – A weak ETag validator 

In typical usage, when a URL is retrieved, the Web server will return the resource’s current representation along with its corresponding ETag value, which is placed in an HTTP response header «ETag» field:

The client may then decide to cache the representation, along with its ETag. Later, if the client wants to retrieve the same URL resource again, it will first determine whether the locally cached version of the URL has expired (through the Cache-Control and the Expire headers). If the URL has not expired, it will retrieve the locally cached resource. If it is determined that the URL has expired (is stale), the client will send a request to the server that includes its previously-saved copy of the ETag in the «If-None-Match» field. [3]

If-None-Match: "686897696a7c876b7e" 

Источник

Оцените статью