http-conditional.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. Enable support for HTTP/1.x conditional requests in PHP.
  5. Goal: Optimisation
  6. - If the client sends a HEAD request, avoid transferring data and return the correct headers.
  7. - If the client already has the same version in its cache, avoid transferring data again (304 Not Modified).
  8. - Possibility to control cache for client and proxies (public or private policy, life time).
  9. - When $feedMode is set to true, in the case of a RSS/ATOM feed,
  10. it puts a timestamp in the global variable $clientCacheDate to allow the sending of only the articles newer than the client’s cache.
  11. - When $compression is set to true, compress the data before sending it to the client and persistent connections are allowed.
  12. - When $session is set to true, automatically checks if $_SESSION has been modified during the last generation the document.
  13. Typical use:
  14. ```php
  15. <?php
  16. require_once 'http-conditional.php';
  17. //Date of the last modification of the content (Unix Timestamp format).
  18. //Examples: query the database, or last modification of a static file.
  19. $dateLastModification = ...;
  20. if (httpConditional($dateLastModification)) {
  21. ... //Close database connections, and other cleaning.
  22. exit(); //No need to send anything
  23. }
  24. //Do not send any text to the client before this line.
  25. ... //Rest of the script, just as you would do normally.
  26. ?>
  27. ```
  28. Version 1.10, 2024-12-22, https://alexandre.alapetite.fr/doc-alex/php-http-304/
  29. ------------------------------------------------------------------
  30. Written by Alexandre Alapetite in 2004, https://alexandre.alapetite.fr/cv/
  31. Copyright 2004-2023, Licence: Creative Commons "Attribution-ShareAlike 2.0 France" BY-SA (FR),
  32. https://creativecommons.org/licenses/by-sa/2.0/fr/
  33. https://alexandre.alapetite.fr/divers/apropos/#by-sa
  34. - Attribution. You must give the original author credit
  35. - Share Alike. If you alter, transform, or build upon this work,
  36. you may distribute the resulting work only under a license identical to this one
  37. (Can be included in GPL/LGPL projects)
  38. - The French law is authoritative
  39. - Any of these conditions can be waived if you get permission from Alexandre Alapetite
  40. - Please send to Alexandre Alapetite the modifications you make,
  41. in order to improve this file for the benefit of everybody
  42. If you want to distribute this code, please do it as a link to:
  43. https://alexandre.alapetite.fr/doc-alex/php-http-304/
  44. */
  45. /**
  46. * In RSS/ATOM feedMode, contains the date of the clients last update.
  47. * Global public variable because PHP4 did not allow conditional arguments by reference
  48. * @var int
  49. */
  50. $clientCacheDate = 0;
  51. /**
  52. * Global private variable
  53. * @var bool
  54. */
  55. $_sessionMode = false;
  56. /**
  57. * RFC2616 HTTP/1.1: https://www.w3.org/Protocols/rfc2616/rfc2616.html
  58. * RFC1945 HTTP/1.0: https://www.w3.org/Protocols/rfc1945/rfc1945.txt
  59. * Credits: https://alexandre.alapetite.fr/doc-alex/php-http-304/
  60. *
  61. * @param int $UnixTimeStamp: Date of the last modification of the data to send to the client (Unix Timestamp format).
  62. * @param int $cacheSeconds (default 0) Lifetime in seconds of the document. If $cacheSeconds<0, cache is disabled.
  63. * If $cacheSeconds==0, the document will be revalidated each time it is accessed. If $cacheSeconds>0, the document will be cashed and not revalidated against the server for this delay.
  64. * @phpstan-param 0|1|2 $cachePrivacy
  65. * @param int $cachePrivacy (default 0) 0=private, 1=normal (public), 2=forced public. When public, it allows a cashed document ($cacheSeconds>0) to be shared by several users.
  66. * @param bool $feedMode (default false) Special RSS/ATOM feeds.
  67. * When true, it sets $cachePrivacy to 0 (private), does not use the modification time of the script itself, and puts the date of the client’s cache (or a old date from 1980) in the global variable $clientCacheDate.
  68. * @param bool $compression (default false) Enable the compression and allows persistent connections (automatic detection of the capacities of the client).
  69. * @param bool $session (default false) To be turned on when sessions are used. Checks if the data contained in $_SESSION has been modified during the last generation the document.
  70. * @return bool True if the connection can be closed (e.g.: the client has already the latest version), false if the new content has to be send to the client.
  71. */
  72. function httpConditional(int $UnixTimeStamp, int $cacheSeconds = 0, int $cachePrivacy = 0, bool $feedMode = false, bool $compression = false, bool $session = false): bool {
  73. if (headers_sent()) return false;
  74. if (is_string($_SERVER['SCRIPT_FILENAME'] ?? null)) $scriptName = $_SERVER['SCRIPT_FILENAME'];
  75. elseif (is_string($_SERVER['PATH_TRANSLATED'] ?? null)) $scriptName = $_SERVER['PATH_TRANSLATED'];
  76. else return false;
  77. if ((!$feedMode) && (($modifScript = (int)filemtime($scriptName)) > $UnixTimeStamp))
  78. $UnixTimeStamp = $modifScript;
  79. $UnixTimeStamp = (int)min($UnixTimeStamp, time());
  80. $is304 = true;
  81. $is412 = false;
  82. $nbCond = 0;
  83. //rfc2616-sec3.html#sec3.3.1
  84. $dateLastModif = gmdate('D, d M Y H:i:s \G\M\T', $UnixTimeStamp);
  85. $dateCacheClient = 'Thu, 10 Jan 1980 20:30:40 GMT';
  86. //rfc2616-sec14.html#sec14.19 //='"0123456789abcdef0123456789abcdef"'
  87. if (is_string($_SERVER['QUERY_STRING'] ?? null)) $myQuery = '?' . $_SERVER['QUERY_STRING'];
  88. else $myQuery = '';
  89. if ($session && isset($_SESSION)) {
  90. global $_sessionMode;
  91. $_sessionMode = $session;
  92. $myQuery .= print_r($_SESSION, true) . session_name() . '=' . session_id();
  93. }
  94. $etagServer = '"' . md5($scriptName . $myQuery . '#' . $dateLastModif) . '"';
  95. // @phpstan-ignore booleanNot.alwaysTrue
  96. if ((!$is412) && is_string($_SERVER['HTTP_IF_MATCH'] ?? null)) { //rfc2616-sec14.html#sec14.24
  97. $etagsClient = stripslashes($_SERVER['HTTP_IF_MATCH']);
  98. $etagsClient = str_ireplace('-gzip', '', $etagsClient);
  99. $is412 = (($etagsClient !== '*') && (strpos($etagsClient, $etagServer) === false));
  100. }
  101. // @phpstan-ignore booleanAnd.leftAlwaysTrue
  102. if ($is304 && is_string($_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? null)) { //rfc2616-sec14.html#sec14.25 //rfc1945.txt
  103. $nbCond++;
  104. $dateCacheClient = $_SERVER['HTTP_IF_MODIFIED_SINCE'];
  105. $p = strpos($dateCacheClient, ';');
  106. if ($p !== false)
  107. $dateCacheClient = substr($dateCacheClient, 0, $p);
  108. $is304 = ($dateCacheClient == $dateLastModif);
  109. }
  110. if ($is304 && is_string($_SERVER['HTTP_IF_NONE_MATCH'] ?? null)) { //rfc2616-sec14.html#sec14.26
  111. $nbCond++;
  112. $etagClient = stripslashes($_SERVER['HTTP_IF_NONE_MATCH']);
  113. $etagClient = str_ireplace('-gzip', '', $etagClient);
  114. $is304 = (($etagClient === $etagServer) || ($etagClient === '*'));
  115. }
  116. if ((!$is412) && is_string($_SERVER['HTTP_IF_UNMODIFIED_SINCE'] ?? null)) { //rfc2616-sec14.html#sec14.28
  117. $dateCacheClient = $_SERVER['HTTP_IF_UNMODIFIED_SINCE'];
  118. $p = strpos($dateCacheClient, ';');
  119. if ($p !== false)
  120. $dateCacheClient = substr($dateCacheClient, 0, $p);
  121. $is412 = ($dateCacheClient !== $dateLastModif);
  122. }
  123. if ($feedMode) { //Special RSS/ATOM
  124. global $clientCacheDate;
  125. $clientCacheDate = @strtotime($dateCacheClient);
  126. $cachePrivacy = 0;
  127. }
  128. if ($is412) { //rfc2616-sec10.html#sec10.4.13
  129. header('HTTP/1.1 412 Precondition Failed');
  130. header('Cache-Control: private, max-age=0, must-revalidate');
  131. header('Content-Type: text/plain');
  132. echo "HTTP/1.1 Error 412 Precondition Failed: Precondition request failed positive evaluation\n";
  133. return true;
  134. } elseif ($is304 && ($nbCond > 0)) { //rfc2616-sec10.html#sec10.3.5
  135. header('HTTP/1.0 304 Not Modified');
  136. header('Etag: ' . $etagServer);
  137. if ($feedMode) header('Connection: close'); //Comment this line under IIS
  138. return true;
  139. } else { //rfc2616-sec10.html#sec10.2.1
  140. //rfc2616-sec14.html#sec14.3
  141. if ($compression) ob_start('_httpConditionalCallBack'); //Will check HTTP_ACCEPT_ENCODING
  142. //header('HTTP/1.0 200 OK');
  143. if ($cacheSeconds < 0) {
  144. $cache = 'private, no-cache, no-store, must-revalidate';
  145. //header('Expires: 0');
  146. header('Pragma: no-cache');
  147. } else {
  148. if ($cacheSeconds === 0) {
  149. $cache = 'private, must-revalidate, ';
  150. //header('Expires: 0');
  151. } elseif ($cachePrivacy === 0) $cache = 'private, ';
  152. elseif ($cachePrivacy === 2) $cache = 'public, ';
  153. else $cache = '';
  154. $cache .= 'max-age=' . floor($cacheSeconds);
  155. }
  156. //header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T',time()+$cacheSeconds)); //HTTP/1.0 //rfc2616-sec14.html#sec14.21
  157. header('Cache-Control: ' . $cache); //rfc2616-sec14.html#sec14.9
  158. header('Last-Modified: ' . $dateLastModif);
  159. header('Etag: ' . $etagServer);
  160. if ($feedMode) header('Connection: close'); //rfc2616-sec14.html#sec14.10 //Comment this line under IIS
  161. return $_SERVER['REQUEST_METHOD'] === 'HEAD'; //rfc2616-sec9.html#sec9.4
  162. }
  163. }
  164. /**
  165. * Private function automatically called at the end of the script when compression is enabled.
  166. * One can adjust the level of compression with zlib.output_compression_level in php.ini
  167. * Reference rfc2616-sec14.html#sec14.11
  168. */
  169. function _httpConditionalCallBack(string $buffer, int $mode = 5): string {
  170. if (extension_loaded('zlib') && (ini_get('zlib.output_compression') == false)) {
  171. $buffer2 = ob_gzhandler($buffer, $mode) ?: ''; //Will check HTTP_ACCEPT_ENCODING and put correct headers such as Vary //rfc2616-sec14.html#sec14.44
  172. if (strlen($buffer2) > 1) //When ob_gzhandler succeeded
  173. $buffer = $buffer2;
  174. }
  175. header('Content-Length: ' . strlen($buffer)); //Allows persistent connections //rfc2616-sec14.html#sec14.13
  176. return $buffer;
  177. }
  178. /**
  179. * Update HTTP headers if the content has just been modified by the client’s request.
  180. * See an example on https://alexandre.alapetite.fr/doc-alex/compteur/
  181. */
  182. function httpConditionalRefresh(int $UnixTimeStamp): void {
  183. if (headers_sent()) return;
  184. if (is_string($_SERVER['SCRIPT_FILENAME'] ?? null)) $scriptName = $_SERVER['SCRIPT_FILENAME'];
  185. elseif (is_string($_SERVER['PATH_TRANSLATED'] ?? null)) $scriptName = $_SERVER['PATH_TRANSLATED'];
  186. else return;
  187. $dateLastModif = gmdate('D, d M Y H:i:s \G\M\T', $UnixTimeStamp);
  188. if (is_string($_SERVER['QUERY_STRING'] ?? null)) $myQuery = '?' . $_SERVER['QUERY_STRING'];
  189. else $myQuery = '';
  190. global $_sessionMode;
  191. if ($_sessionMode && isset($_SESSION))
  192. $myQuery .= print_r($_SESSION, true) . session_name() . '=' . session_id();
  193. $etagServer = '"' . md5($scriptName . $myQuery . '#' . $dateLastModif) . '"';
  194. header('Last-Modified: ' . $dateLastModif);
  195. header('Etag: ' . $etagServer);
  196. }