Slim is slow to serve images

Hi, I was wondering if anyone could offer some insight into an issue I’m experiencing with Slim(3).

I’m using routing to server assets, in this case an image, but with Slim the TTFB is at minimum 5 seconds for a 2k file. Obviously unacceptable :yum:.

The code is as follows:

  $loadImage = '/some/path/to/an/image.png';
  $fh = fopen($loadImage, 'rb');

  $stream = new Stream($fh);

  return $response
      ->withHeader('Content-Type', 'image/png')
      ->withHeader('Content-Transfer-Encoding', 'Binary')
      ->withHeader('Content-Length', filesize($loadImage))
      ->withHeader('Expires', '0')
      ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
      ->withHeader('Pragma', 'public')
      ->withBody($stream);

…however, if I have a separate PHP file to do the rendering, it takes then 300ms:

$loadImage = '/some/path/to/an/image.png';

header("Content-type: image/png");
header("Expires: Mon, 1 Jan 2099 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Content-Length: ".filesize($loadImage)." bytes");
readfile($loadImage);
exit();

At first I thought it was caused by switching to HTTP2 (Apache 2.4.38, PHP 7.2.14) but the direct approach to display the image invalidates that theory. Any ideas as to why Slim is taking so long to display the image?

I’ll add that the image is being accessed by NFS

Thanks :slight_smile:

Hi!

I have tried your code with the following results:

PNG image with 2.2 MB

  1. With Slim Stream
  • xdebug enabled: 2300 ms
  • xdebug disabled: 260 ms
  1. With header/readfile
  • xdebug enabled: ~1000 ms
  • xdebug disabled: ~220 ms

At the end, without xdebug, the result was nearly the same.

Maybe just xdebug and/or other middleware(s) could be the bottleneck here.

Edit: Updated png file size