How to detect if browser supports WebP format on server side PHP script?

April 25, 2020

We can make use of PHP global variable $_SERVER to do so.

Here’s another related post about PHP global variable $_SERVER.

How to get the full URL of current page in PHP?

Using $_SERVER[‘HTTP_ACCEPT’] we can get the detailed contents of the Accept: header, if there is one available.

Then we can use PHP strpos() function to check if it has image/webp in it. If so, it’s supported.

Here’s how we can do that:

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

Just change the true to false if you want to check if webp is not supported OR just use else in the previous example.

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

Use this code to check if webp is supported or the browser is chrome

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

Credit: Stack Overflow


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

PHP Login System using PDO Part 2: Login using Email or UsernamePHPA Quick Comparison of JOIN and Subquery in SQLSQL/MySQLHow to Use the EXISTS and NOT EXISTS Operator with a Subquery in SQL and MySQL?SQL/MySQLHow to uninstall Cocoapods from the Mac OS?MiscLearn to Establish Connection using MySQLi (object-oriented), MySQLi (procedural) and PDO with Example CodePHPHow to implement NSNumberFormatter in Swift for currency?SwiftMySQL queries to get data rows from previous month as well as from last 30 daysSQL/MySQLFive common features of Angular template syntax (with examples)AngularHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressWhat is XP (Extreme Programming) and When should it be used?MiscCheck if any column has NULL values in PostgresPostgres