0

I am trying to get client hint headers in PHP. These need to be opted in. I do that using header() function. After that I read the header. Now here is the problem: the first time I open the website it is not able to read that header. If I refresh the page, PHP can access the header and everything works. I inspected the Network tab in Chrome and the device-memory is not being sent on first request. On the second however it is.

If I try to run this code in an online sandbox, it always fails to read the requested header.

Here is the code I have used:

<?php

header("Accept-CH: Device-Memory");
header("Accept-CH-Lifetime: 86400");

$headers = getallheaders();

if (isset($headers['device-memory'])) {
  echo 'Your device has approximately ' . $headers['device-memory'] . ' GiB of RAM.';
} else {
  echo 'No information about RAM available.';
}
Andris Jefimovs
  • 689
  • 6
  • 17
  • This is as per the design, isn't it? The Client Hint request headers aren't sent by default, they are only sent on the request AFTER you include the Accept-CH response header (see https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/client-hints). – Matt Raines Jun 12 '21 at 15:41
  • The getallheaders() array is case sensitive. In my case I had to use $headers['Device-Memory']. – Matt Raines Jun 12 '21 at 15:43
  • @MattRaines If I look at the output of `var_dump(getallheaders())`, the `device-memory` value is lowercase. – Andris Jefimovs Jun 12 '21 at 15:51
  • @MattRaines So now I tried to opt in the header and reload the page by adding a parameter to the URL. If there is the parameter, I read `Device-Memory`. It seems to work now. – Andris Jefimovs Jun 12 '21 at 16:19

1 Answers1

0

The client will then make future requests using a header field containing these details [...]

From Wikipedia

So to access on of client hint headers one can send the Access-CH header and reload the page:

<?php

header('Accept-CH: Device-Memory');

if (!isset($_GET['opted'])) {
  header('Location: ./?opted');
}

$headers = getallheaders();

if (isset($headers['device-memory'])) {
  echo 'Your device has approximately ' . $headers['device-memory'] . ' GiB of RAM.';
} else {
  echo 'No information about RAM available.';
}

PHP will send the header and reload after adding the ?opted parameter.

Andris Jefimovs
  • 689
  • 6
  • 17