Detect if browser supports WebP format? (server side)

There is already a thread discovering WebP support using the client side. How to detect WebP support using the server side?

+4
source share
2 answers

Today you should check the accept header for image/webp . All browsers that support WebP will send this as part of the accept string for all requests (images and images). In short:

 if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false ) { // webp is supported! } 

(you can use preg_match instead, and add text border checks and case insensitivity, but this should be fine in the real world)


Here is my original answer from a few years ago when the above was not reliable

The "correct" way is to check the accept header that is being sent, but an error in Chrome means that it will not list image/webp even if it supports it.

This is a relevant forum topic: https://groups.google.com/a/webmproject.org/forum/#!topic/webp-discuss/6nYUpcSAORs

which refers to this bugtracker: https://code.google.com/p/chromium/issues/detail?id=169182 , which in turn refers to this: https://code.google.com/p/ chromium / issues / detail? id = 267212

Final result? While not yet implemented, Google Chrome will soon explicitly list image/webp as the accepted type for image requests and without an image. This way your script that serves HTML can check this out. Opera is already sending image/webp as part of its standard accept header (again, regardless of whether it is an image request or not).

So you can check like this:

 if( strpos( $_SERVER['HTTP_ACCEPT'], 'image/webp' ) !== false || strpos( $_SERVER['HTTP_USER_AGENT'], ' Chrome/' ) !== false ) { // webp is supported! } 

(Instead, you can use preg_match , as well as add text border checks and case insensitivity, but in the real world this should be good. You can also check at least version 6 of Chrome, but pretty much no one is running the outdated version, so there is not much point)

+11
source

Dave answers well, but does not work with all browsers. I am using this method:

 function GetBrowserAgentName($user_agent) { if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera'; elseif (strpos($user_agent, 'Edge')) return 'Edge'; elseif (strpos($user_agent, 'Chrome')) return 'Chrome'; elseif (strpos($user_agent, 'Safari')) return 'Safari'; elseif (strpos($user_agent, 'Firefox')) return 'Firefox'; elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer'; return 'Other'; } 

So, after checking the browser:

  $BrowserAgentName = GetBrowserAgentName($_SERVER['HTTP_USER_AGENT']); If ($BrowserAgentName == 'Chrome' || $BrowserAgentName =='Opera') { // webp is supported! } 

Here I just add Opera and Chrome, you can use a deeper detector for the browser version and add if {} to your agent. But you need to update this code as a browser update to support image / webp.

+1
source

Source: https://habr.com/ru/post/1496327/


All Articles