http-conditional.php 9.6 KB

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