Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Browser HTML5 Compatibility with PHP

I want to use input types or other features from HTML5. But not all browsers support these HTML5 features.

How can I check if a user's browser is html5 compatible with PHP code only?.

By the way, I don't like modernizr. I have to figure out with PHP.

Example:

Html5 compatible browser:

<input type="date" value="" />

Html5 incompatible browser:

<input id="datepicker" type="text" value="" />
like image 438
Bora Avatar asked Dec 04 '22 10:12

Bora


1 Answers

PHP is really the wrong place to be doing this kind of detection. There are any number of reasons why it's a bad idea, and they're well documented in many places.

The key to successfully working with browser compatibility is to detect support for the features you need, and either polyfill or gracefully degrade those specific features. Detecting the actual browser or browser version is poor practice and is likely to give you problems with both false positives and false negatives. Since the whole point of the exercise is to avoid compatibility glitches, having inaccurate results makes the whole thing somewhat self defeating.

For feature detection, Modernizr is a great little tool, but if you really don't get along with it as you say in the question, here's a tiny little JS function that specifically detects support for the date input field type:

/**
 * @returns boolean - True if browser suppors 'date' input type.
 */
function browserSupportsDateInput() {
    var i = document.createElement("input");
    i.setAttribute("type", "date");
    return i.type !== "text";
}

As you can see, it really is simple stuff. (You can find it documented in more detail here, by the way)

With that function in your site, it now becomes extremely easy to polyfill the date field.

Here's your HTML:

<input type='date' name='whatever' class='datepicker'>

Now you can have a tiny bit of jQuery that does the following:

$(function() {
    if(!browserSupportsDateInput()) {
        $(".datepicker").datepicker();
    }
});

Simple as that.

Of course, Modernizr would make it better. Modernizr doesn't do the polyfill itself, so you'd still need code similar to the above to apply the datepicker plugin if the date input type wasn't supported, but what Modernizr does which I haven't done in my code above is to allow you to tell the browser to only bother loading the datepicker library if it's needed. This would save a lot of bandwidth for modern browsers. Modernizr makes this kind of thing dead easy.

Hopefully the above will give you some food for thought about the best way to do this kind of thing. It's all about best practice. If you feel you must do it in PHP, then so be it, but just be aware that you're going against the recommendation of pretty much every expert out there, and it will give you more headaches in the long run.

like image 96
Spudley Avatar answered Dec 06 '22 22:12

Spudley