I am trying to utilize HTTP 100 continue with preload headers to preload some content to browsers.
The issue is that I am not getting the expected result.
Here is my sample code:
header('HTTP/1.1 100 Continue');
header('Link: </assets/style.css>; rel=preload');
header('Link: </assets/app.js>; rel=preload');
header(''); // send empty line to end 100 continue section
flush();
sleep (4); // Emulate some processing while browser is preloading assets
header('HTTP/1.1 200 OK');
echo "aaa\n";
echo "bbb\n";
flush();
exit;
But instead of expected response of:
HTTP/1.1 100 Continue
Link: </assets/style.css>; rel=preload
Link: </assets/app.js>; rel=preload
HTTP/1.1 200 OK
aaa
bbb
I am getting this:
HTTP/1.1 200 OK
Date: Wed, 04 Oct 2023 15:21:24 GMT
Server: Apache/2.4.57 (Ubuntu)
Link: </assets/app.js>; rel=preload
Upgrade: h2,h2c
Connection: Upgrade
Vary: Accept-Encoding
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
aaa
bbb
Am I missing something?
Do I need something more than just flush() to send the 100 continue header?
My current stack is apache + php-fpm.
And command I use is curl -i https://localhost/
Also I will be using this with a symfony project so I need to make sure to reset headers_sent() after the 100 continue section, or symfony will just not send anything (the send function starts with if(headers_sent()) return;),
But I am not sure how to reset it after the first flush.
Preloading just tells the browser ahead of time that some resources need to be fetched, which reduces load and possible render time of a page.
Usually your browser loads css/js/images/etc when they are read from the html, which happens parsed, line by line. If your html is large, you can tell the browser to load some resources before the browser has seen them in the HTML (because it has seen them in the response headers).
You don't need to flush the content first, the headers are ALWAYS read before the html is read. As soon as the browser sees a preload, it starts pulling that file, even before the html is parsed.
The only thing you need to do is applying those headers, ahead of time. That's why most frameworks don't use
<?php echo "<html>" ?>because now you can not send any headers anymore. Html responses are deferred, so you know which resources are required for a page, so you can add those response headers.Since you tagged
symfony, it seems that a Controller has a method calledaddLink, which does this for you.https://symfony.com/doc/current/web_link.html#resource-hints