How to specify a “Last-Modified” header in PHP

422 Views Asked by At

I am building a website that uses PHP, and would like to know how to send a Last-Modifed header that reflects the actual date that my files were last modified. As I'm sure you know, PHP strips away the Last-Modified header by default, meaning that the page is always considered fresh.

In order to take advantage of caching, I wish to apply PHP to manually send a Last-Modified header to reflect when the containing PHP file was last edited.

I have looked on the web and have found no satisfactory examples. Any code examples of how to achieve this would be gratefully appreciated.

(Please accept my apologies in advance if this sounds like bit a novice question.)

1

There are 1 best solutions below

5
Marcin Orlowski On BEST ANSWER

As I'm sure you know, PHP strips away the Last-Modified header by default

Nope.

$ cat test.php
<?php
\header('Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT');

$ php -S 127.0.0.1:6969 test.php
[Fri Apr 14 00:25:18 2023] PHP 8.1.17 Development Server (http://127.0.0.1:6969) started

and then

$ curl -v http://localhost:6969/1.php

*   Trying 127.0.0.1:6969...
* Connected to localhost (127.0.0.1) port 6969 (#0)
> GET /test.php HTTP/1.1
> Host: localhost:6969
> User-Agent: curl/7.85.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Host: localhost:6969
< Date: Thu, 13 Apr 2023 22:24:10 GMT
< Connection: close
< X-Powered-By: PHP/8.1.17
< Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT
< Content-type: text/html; charset=UTF-8

It gets returned as expected:

< Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT

EDIT To get the real modification date use filemtime():

$modified = \date("F d Y H:i:s.", \filemtime($filename));
\header("Last-Modified: {$modified}");