Not all of browsers can support webp images, we should only display webp images in browsers that only support webp format. In this tutorial, we will introduce how to detect a browser can support webp image or not by php.
To understand display image by using php, we can refer:
PHP Show Images (PNG, GIF, JPEG, WebP) in Browsers: A Completed Guide
How to detect a browser can support webp image or not?
We can find the way by checking http request header.
As to http request header:
We can find a header called accept, which contains some information about whether a browser can support webp image or not. We can check the value of it to find the answer.
How to get the value of http request header accept?
We can use code below to the this value:
<?php $accept = $_SERVER['HTTP_ACCEPT']; echo $accept; ?>
Run this code, we can get this value.
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Then we can detect whether this browser support webp format or not.
<?php $support = false; if(isset($_SERVER['HTTP_ACCEPT'])){ $accept = $_SERVER['HTTP_ACCEPT']; $pos = stripos($accept, 'image/webp'); if($pos === false){ $support = false; }else{ $support = true; } } if($support){ echo "this browser supports webp images"; } ?>
Run this code, we can find our browser support webp images.