slimphp / Slim

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs.
http://slimframework.com
MIT License
11.94k stars 1.95k forks source link

Slim 4 - Unable to set Expires headers with Middleware #3279

Closed vladaman closed 1 year ago

vladaman commented 1 year ago

I'm facing an issue while attempting to develop a caching middleware within Slim 4.11. It appears that regardless of whether I'm using the withHeader or withAddedHeader methods, there might be a conflict resulting in header overwriting. Please notice that the Allow header is actually passed through. Could anyone provide insights into potential factors causing this header overwrite problem?

// middleware.php:
return function (App $app) {
    $twig = Twig::create(__DIR__ . '/../templates', ['cache' => false]);
    $app->add(TwigMiddleware::create($app, $twig));
    $app->add(CachingMiddleware::class);
};
class CachingMiddleware implements Middleware
{
    public function process(Request $request, RequestHandler $handler): Response
    {
        $seconds_to_cache = 3600;
        $ts = gmdate("D, d M Y H:i:s", time() + $seconds_to_cache) . " GMT";
        $response = $handler->handle($request);
        $response = $response->withAddedHeader('Pragma', 'cache') // doesn't work
                             ->withAddedHeader('Expires', $ts) // doesn't work
                             ->withAddedHeader('Cache-Control', sprintf("max-age=%d",$seconds_to_cache)) // doesn't work
                             ->withAddedHeader('Allow', 'xPUT'); // works !
        return $response;
    }
}

Response:

HTTP/1.1 200 OK
Date: Mon, 07 Aug 2023 09:40:16 GMT
Server: Apache/2.4.52 (Ubuntu)
Pragma: no-cache
Expires: Mon, 07 Aug 2023 10:40:16 GMT
Cache-Control: no-store, no-cache, must-revalidate, max-age=0
Cache-Control: post-check=0, pre-check=0
Allow: xPUT
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: 
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
Content-Type: text/html; charset=UTF-8

Using:

vladaman commented 1 year ago

I found the issue from Slim Skeleton app in src/Application/ResponseEmitter/ResponseEmitter.php which was still in our project. This overrides cache headers.

https://github.com/slimphp/Slim-Skeleton/blob/b89cceac915d935f84e4db3201eb9bf9f9caa96f/src/Application/ResponseEmitter/ResponseEmitter.php#L27