In today’s world, serving different content to desktop and mobile clients became de facto standard, at least for newly developed web sites. It presents many new tasks before developer and one of them is how to successfully detect if visitor uses desktop of mobile client. We will set aside the discussion about what is mobile and what is not and focus only on detecting if a client is a phone/tablet or not. For that we use regular expressions with pattern that enables us search environment variable HTTP_USER_AGENT for multiple strings at once. We also check if client accepts WAP and if environment variables HTTP_PROFILE and HTTP_X_PROFILE are empty. Here’s the code:
Now let’s analyze it:
First line contains $wbcnl function that clears line break and carriage return characters (chr 10 and chr 13) which we do not need in returned code.
In lines 2, 3 and 4 we assign values to variables rxstr (the string to be searched to which we assign the value of environment variable HTTP_USER_AGENT) and rxp (regular expression pattern that contains all string patterns that will be searched for). We split assigning value to rxp in two lines for better readability. To add new devices you should only modify line 4 by adding new device name preceded with function | (e.g. |YourNewDevicePattern) between word "treo" and square bracket.
In line 5 we execute regular expression search and store the total number of occurrences of ANY pattern string in variable "MCount" (so, if none of patterns was found MCount will be zero)
Line 6 checks if client accepts â€oapplication/vnd.wap.xhtml+xmlâ€? and assigns the result in variable â€owapâ€? (zero if it does not or positive number if it does).
Line 7 checks the length of combined environment variables HTTP_PROFILE and HTTP_X_PROFILE and assigns result to variable â€olprofâ€? (again zero if both are empty).
In line 8 we sum all three results so if any of the tests was successful the final result will be greater than zero and that would mean that client is a mobile device.
Line 9 simple closes function $wbcnl opened in first line.
Now let’s use this code for actual testing. Save the code in file named checkmoble.ic in your web’s document root and place the following line in FormFields section of page that will be used for detecting device type:
Upon processing file checkmobile.ic, if any of the tests were successful and result is not zero, WhizBase will redirect client to directory â€omobileâ€?, else it will redirect client to directory â€odesktopâ€?.
Thank you for reading; we hope you’ll find good use for this piece of code.