Opt in CH header on first request

657 views Asked by At

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.';
}
1

There are 1 answers

0
Andris Jefimovs On

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.