PHP mobile browser detection? - php

I'm in need of a way to detect mobile browsers server-side. I'd like a way that requires me to do little to set up and little to maintain, yet still provide me with accurate detection of (at the VERY least) Android, Mobile Safari and Blackberry browsers, along with alternatives like Opera.
I'd like to have at least the majority of the mobile market covered, and I'd really prefer virtually all of the market if it doesn't take much.

WURLF is the ultimate way for mobile browser detection and a PHP API is available.

I found this one to be very easy to use php-mobile-detect

(edit: for now the Browser Capability Project is closed, i.e. atm this answer is not an option)
All you need is get_browser() and a recent browscap.ini that maps the user-agent string to a browser/version and its capabilities.
You can get a usually very up-to-date browscap.ini version from http://browsers.garykeith.com/downloads.asp

Its just a matter of reading the headers ( How do I read any request header in PHP ) and parsing / interpreting this to read the "user-agent", you may be able to find an existing PHP script or maybe just plain regex that will help in figuring out which user-agents are mobile and which are regular pc's / laptops.
There are a lot of different headers, as it indicates the operating system, so as many different mobile OS'es as there are there would be user-agent headers so the script needs to have a list of all valid ones.
http://en.wikipedia.org/wiki/List_of_user_agents_for_mobile_phones

Found this library a little while back:
http://code.google.com/p/mobileesp/
Has PHP, Java, JavaScript, and C# versions. I see it as a "lightweight" smartphone/tablet detection tool without dependencies and is regularly updated. I have mixed feelings about it though as some aspects of the code quality are a bit shaky.
If you need something even lighter-weight, the WP Super Cache plugin for WordPress contains some long regex strings you could probably swipe.
Browser sniffing based on user agent strings is always going to be flaky. I looked at WURFL and it is several MB compressed. Using that is overkill. A better approach is to detect the top devices in use on the website, design for those devices, and then call it a day.

A quick Google search picks up these:
http://mobiforge.com/developing/story/lightweight-device-detection-php
http://code.google.com/p/php-mobile-detect/

Zend Framework introduced Zend_Http_UserAgent lately.
It can determine the Mobile Device and it's capabilities by detecting the UserAgent through Wurfl, TeraWurfl and DeviceAtlas API.

How about http://code.google.com/p/hdapi/ ? Server side mobile detection in PHP.

Unfortunately WURFL is not free anymore for commercial projects.
But there is OpenDDR with its experimental PHP implementation.

I once used to store temporarily visitors' ip-addresses and csrf-session values (meant to count current visitors).
And I noticed that I had a side-gain of being able to see if the visitor used a mobile or a PC: The csrf of a mobile changes with every new page load, a PC doesn't; and the ip-addresses remain in both cases.
Sure, you only detect a mobile if a visitor clicks twice and I have not checked how reliable this is (as I do not really need it), but it is php/server-side only.

Related

Is it better/faster to detect mobile browser on server side (PHP) or client side (Javascript)?

I've seen code that detects whether someone is using a mobile browser in Javascript (e.g. a jQuery script) and I've seen some that work in PHP (or other server-side language). But I've never seen a good explanation for whether one is a better choice than the other in all or any situations. Is there a reason why one is a better choice?
The typical answer: it depends on why you are doing the check...
From my standpoint, here is what I usually consider:
If you want to present the user a different experience (mobile, tablet, laptop, etc) based on browser, do it at the server.
If you want to present the same general experience, but need to account for browser compatibility issues, do it at the client.
It is also considered by some in the UX field to be "bad form" to present the user an empty page and fill it in dynamically. Instead, a preliminary page should be populated and content can be dynamically added or altered. If this is a concern for you, a combination of server side and client side may be necessary.
I'd say the better way would be on server side, because for Javascript you need to wait until the page is rendered, while on server side it happens before.
If you're trying to detect this in order to do decide what javascript features are available, you'll have greater accuracy, without any major loss of speed if you do this in JavaScript.
If you're going to completely change what sort of page is rendered, like a full website or a mobile website, you're better off doing this server side.
As Ricebowl stated, never trust the client. However, I feel that it's almost always a problem if you do trust the client. If your application is worth writing, it's worth properly securing. If anyone can break it by writing their own client and passing data you don't expect, that's a bad thing. For that reason, you need to validate on the server.
Is green better than red?
Everything has its benefits and drawbacks. For example, doing it server side is more reliable, doing it client-side means less work for the server.
In fact, the client may have JavaScript disabled (see the NoScript extension for Firefox, and ScriptNo for Chrome, that allows a smart user to only enable JS on sites where you actually need it - a nice side effect is that it also eliminates almost all ads these days, as they largely seem to rely on JS from third party domains now). So just using the User-Agent string is more reliable, but less flexible.
If you work JS-heavy, you might get away with a dumb server, i.e. you do not need slow PHP, but you can serve all your data with high-performance static serving, through the various CDNs etc. - but anything that requires JS will work less good with search spiders, and some users will likely just block it.
As a web developer, UX and UI programmer I figure if anyone wants to change their UA, it's fine. They get to deal with the incompatibilities. As for a mobile vs desktop I would recommend the light version of browscap.ini instead of searching for device check for ismobiledevice. The if statement will be true or false, then you can also check tablet also. In the if mobile clause check the istablet key in the associative array. You can use it for phone or tablet css.

User agent string for "[browser version] and later"

I'm trying to avoid tons of PHP code by specifying that a remote stylesheet, containing CSS animation, should be loaded if the HTTP_USER_AGENT string corresponds to [browser version x] or later. For example, knowing that CSS animations are supported in Chrome 19 and newer, the code would detect if Chrome's version is greater than 19, and load the appropriate stylesheet.
Is this feasible at all using PHP?
This is one solution, but you will have to update your parser for the user agent string from time to time to include changes therein.
There is no agreed standard for use agent strings, so in general parsing the user agent string is quite hard and often comes down to lookup tables.
A more future-proof approach would be to detect the support of CSS animations on the client side using, e.g., Modernizr and then load the stylesheet based on the result. That way you don't care, if some browser developer wants to change the (structure of the) user agent string in the future.
If you must use PHP for this, then there is a built-in function get_browser() that does what you want.
However... If you use get_browser(), be aware that it is a bad solution to your problem.
In order to user this function, you must have an up-to-date browsecap.ini file, which is basically a text file that defines the capabilities of every browser and every version ever released.
The downsides of this are obvious:
You have to find and install an up-to-date copy of browsecap.ini in the first place.
You have to update it every time a new browser is released (and new versions are coming out frequently, so this is quite a big task).
It might not include all features that you want to detect.
It will break if the user masks their user agent string.
For all these reasons, I strongly recommend not using get_browser(), or indeed any PHP-based or server-side solution.
Instead, as others have said, you should investigate using the Modernizr library. This is a Javascript library that you install on your site that does feature detection in the browser. It will never be out of date, because it looks specifically at whether the features are supported, so it doesn't care what the actual browser is.
You may wish to consider using a Device Description Repository (DDR). This is an application or Web Service that you can pass in an User Agent String and get a list of known capabilities for that User Agent.
The benefits to this is that you will not have to keep updating your own code as new User Agents come about.
I read about DDRs recently in Dino Esposito's MSDN article on Mobile Site Development. He has an excellent write-up on the capabilities and nature of DDRs.
I realize you are doing PHP, but connecting / querying a DDR should be language independent.
Just a thought, hope this helps.

Detect mobile devices - and tablet devices

I am currently looking at some code for PHP detection of mobiles, which is probably quite easy.
Now I just have got one problem - I want to make it possible to make unique view-files in my MVC-framework for tablets, mobiles and web pages. So I need to split the tablet from the rest of the mobile devices.
Currently this is the code, that I am using:
public function isMobile()
{
if(preg_match('/(alcatel|amoi|android|avantgo|blackberry|benq|cell|cricket|docomo|elaine|htc|iemobile|iphone|ipad|ipaq|ipod|j2me|java|midp|mini|mmp|mobi|motorola|nec-|nokia|palm|panasonic|philips|phone|sagem|sharp|sie-|smartphone|sony|symbian|t-mobile|telus|up\.browser|up\.link|vodafone|wap|webos|wireless|xda|xoom|zte)/i', $_SERVER['HTTP_USER_AGENT']))
return true;
else
return false;
}
But this is not enough - the only check is wheter the device is a mobile device - if not it is as standard telling the framework, that we're on a computer. The last part is ok - but I want to make a split of the mobile devices in actual mobiles - and in a secound group, which should be tablets.
I hope, that I have made my wish clear, and I hope, that you have some input in a good way to achieve this.
Thanks in advance.
Here is a class with methods for detecting each platform individually.
https://github.com/serbanghita/mobile-detect
Old question, but here goes my opinion regarding mobile detection.
You state in your question that you want unique files for mobile devices, so I can assume the reason for this is to present a different version of the website for mobile clients and desktop clients.
This approach is OK until a certain point. And that point is called Android. There are ~1.5 million Android devices activated each day with resolutions from 320*240 to 2560*1600, which makes it hard to if {} else for each of them. Even if you try to make a list with most used devices and you try to target only those, it will be hard to support a new device in the future.
My approach a while back was to forget about old method of splitting devices into "mobile" and "desktop" categories and create a new method. And that method consist in "good" and "bad" browsers which is based on browser capabilities. For example, if the browser supports local storage, it will be in "good" category.
Starting from this, I had the possibility to create a "base" version of the website, very basic from a UI standpoint but which will work cross-browser. This base version of the website will present the same content (because that matters at the end of the day) on all devices, will be very small in size (less assets, smaller html) and based on browser capabilities will be enriched on the client side.
So in the end you will end up with a website that has very small footprint (html size and assets), that looks OK cross browser and it will support any new device that comes up on the market without any changes, will load fast even on poor connections and that can be enriched on client side based on browser capabilities.
You can even enrich the webpage based on devices size: if the browser reports a large screen, you can bring in more assets, more ads and make the webpage more beautiful ; if the browser reports is on a small screen, you leave it as is.
Mobile_Detect is a lightweight PHP class for detecting mobile devices (including tablets). It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment. — Read more
http://mobiledetect.net
You can also use a more comprehensive solution like WURFL Cloud, which is a service that detects the capabilities of mobile devices, like is_mobile and is_tablet. There is a free plan for low traffic sites: http://www.scientiamobile.com/cloud

What is the best approach to geo targeting?

Lately geo-targeting has been pretty popular in technology. By IP, cell tower, GPS, using browser plugins, HTML5?, mobile devices ...
Since I'm about to add some geo-targeted features on our site, I wanted to know what's the best approach. Is there some API that uses a mix of all those technologies? Or at least, what API/service would you recommend I use?
The service I'm working on doesn't need to be 100% accurate, so I'm OK with geo-IP, but if there's an easy way to do better, why not.
Technologies used are php, javascript, ajax, java.
Whatever you do please please please don't set the language of your website based on the user's IP, and then make it almost impossible to change unless you know said language and you feel like wasting hours (like ebay and paypal, among others, do). Use the browser's language.
Not everyone in, let's say, France speaks or wants to speak French.
I guess it's not very related to your question but i felt the need to rant about this, sorry :)
GEO IP is probably the best approach for now.
HTML5 looks promising, but it'll be a while before it's widely supported. And even then it requires explicit user approval, which kind of limits the possibilities for using it (for example auto-redirecting to a country specific version of a website)
For a start try the free http://api.hostip.info?ip=x.x.x.x (www.hostip.info for website)
It'll give you city and country in a xml structur. I've a small proxy-script writen in PHP on the http-server, which a html page calls with ajax and show the infomation in text and on a Google map using the Google geocoding api. Later on you can easy replace the api.hostip.info with an other api.
I would use IP address detection by default, and then optionally ask for a more specific location using the Javascript/HTML5 navigator.geolocation API when present. (For example, in iPhone Safari)
Most users are still using devices that don't know the location themselves, so plugins that are available will not get a better location than IP address detection does anyway. (Alternatively, they'll prompt users to manually enter data, which is annoying)
Max Mind is good. But if you are looking for a free solution, you may want to consider using the javascript geocoder. Eventually they will support addresses and country, but right now, they only give you a latitude and longitude.

Changing web content based on browser type

I'm writing a web application and I'd like to work out what type of browser/OS the request is coming from, and customise the returned content accordingly. So if someone visits the site from an iPhone/Android, they get a more streamlined experience, or if it's a desktop, they get the full version. I will pretty much take a completely different path, rather than try to mix the content together.
What is the recommended approach for this in ASP.NET/IIS and PHP? Is there a single place I can catch incoming HTTP requests, make a decision, then redirect? Or is this usually done on a page by page case? Any gotchas I should look out for?
Edit: A good point was made to make sure there is a link to the full version on the reduced version. That's a good point, but raises the problem that once the user make this choice, all future redirections now have to point to the full version. I'd really rather be doing all of this in one place.
Cheers,
Shane
ASP.NET has a built-in browser detection mechanism. It's driven by a fully extensible collection of XML files (*.browser) that contain regular expressions for matching the incoming User-Agent string and associated properties for the matched agents.
You can access the properties from the Request.Browser object; you can also tag control properties based on browser specifics.
There's a bunch of info on the Web about this -- I also cover it in detail in my book: Ultra-Fast ASP.NET.
Not a direct answer but it's worth checking out CSS media types. You can specify the handheld type to streamline the page for phones and other small screened devices.
http://www.w3.org/TR/CSS21/media.html
You could take a look at the UserAgent header in the HTTP request and redirect accordingly.
In PHP that would be $_SERVER['HTTP_USER_AGENT'].
You should however watch out that you don't write a lot of duplicate code when doing this.
For ASP.NET applications you can check out the Global.asax file and Session_BeginRequest event.
You should probably look at Conditional Comments:
http://msdn.microsoft.com/en-us/library/ms537512%28VS.85%29.aspx

Categories