javascriptphpimagehttphttp-accept-header

How to check if browser accepting webp images?


I am using $_SERVER['HTTP_ACCEPT'] and after I can check if browser supporting webp images. But when I sending ajax request and trying to get the $_SERVER['HTTP_ACCEPT'] it's returning application/json, text/javascript, */*; q=0.01.

How can I check if client browser accepting webp images?


Solution

  • The browser only tells the server what it's prepared to accept as a response for the current request it's making.

    So if it's making an AJAX request to get some HTML or JSON data to display on the page, then that's what it'll ask for in the accepts header. If the request is specifically for the image (e.g. the request generated by putting an <img tag on the page), then it's that request which will contain the list of acceptable image file types.

    If you're trying to decide whether to supply a webp or png image URL in your JSON, that isn't really going to work.

    Your alternatives are:

    a) provide a link to a single URL which reads the "accepts" header and and then decides whether to return webp content or png content, and fetches the correct content and sets the correct headers to return it to the browser (as if it had requested the image file directly) - this could be implemented by a PHP script for example.

    b) provide URLs for both the png and webp options in your JSON, and then when you're displaying the image, use the HTML <picture> tag to provide the browser with both options (plus a fallback for browsers which don't support the picture tag either), and let the browser choose what to use, based on what it knows it supports.

    e.g.

    <picture>
      <source type="image/webp" srcset="flower.webp">
      <source type="image/jpeg" srcset="flower.jpg">
      <img src="flower.jpg" alt="">
    </picture>
    

    See https://web.dev/serve-images-webp/ and https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture for more info on option (b).