• About Us
  • Blog
  • Basket
  • Account
  • Sign In
  •  

Blog

Published on Friday, August 19, 2011

Create Your Own .NET Mobile Detection Cloud Service to use with PHP

51Degrees.mobi Foundation is one of the most used mobile device detection libraries for .NET available. But what if you’re not using .NET? Thanks to the magic of web services you can have all the advantages of an expensive cloud service for the free and use it with PHP, Java, Ruby, Python and anything else that can consume web services. In this article we’ll be looking at doing this from PHP. This guide assumes you are able to host both a ASP.NET and a PHP site."But I've never worked with .NET"No problem - as is our way at 51Degrees.mobi we've made it as simple as can be: 


Step 1 - Understanding Your Cloud

We advise hosting your own cloud service rather than using a service from us because of the inherent risks in relying on someone else's servers. Using an external service means having to send data to another far away server, waiting for it to be processed and then waiting for a reply. This adds a huge overhead to your website's performance and it’ll never be as fast a local solution, as foundation is in ASP.NET. There is also added risk that their Cloud Server won't be available. Therefore we strongly recommend having your PHP site and .NET as close together. However, for the purposes of showing the process in this guide and for debugging you can use our demo detector service (demos.51degrees.mobi/detector/mobiledevice.asmx). 

To create the cloud we'll be using our open source Foundation Detector sample to create the web service. You can see an online demo of it here. This site is an example of how to configure the foundation and to show detection and redirection in action. It also has a .asmx file defining a SOAP web service that can be used to interrogate any capability and useragent, not just the useragent of the browser viewing the site. Consuming a service is just as easy as initialising a class.If you're unfamiliar with Visual Studio and .NET that doesn't matter. The code is already functional and configured, all you need to do is publish the detector site and host it.Note – PHP and ASP.NET are often hosted on different server software, ie Apache and IIS. However, PHP can be used with either server. For my tests I used IIS to do the hosting. See this link - http://php.iis.net/. Microsoft WebMatrix can also be used which provides a nice IDE and sees to all the behind-the-scenes configuration.

Step 2- Testing your Cloud

You can test if the Detector is running easily enough by visiting it in your browser. You should see if checkUA.aspx is working. This page uses the webservice that will be used in PHP later to find information about useragents. You can also visit MobileDevice.asmx itself.This pages lists the methods available to use in the web service. If you can see this you're ready to start using it with PHP.

Step 3 - Accessing your Cloud

Now that your service is running all you need to do is include these functions in your PHP page:

 
//Retrieves the SoapClient and saves the WSDL file locally for performance
//reasons.
function GetSoapClient()
{
    //Constants to find and save WSDL file. You should change the Url to your own service. Don't forget '?WSDL', that is very important
    $filePath = "51DService.xml";
 
    //Obtain WDSL file
    try
    {
        if(!file_exists($fileName))
        {
            //File doesn't already exist
            //Open the url and save xml contents to a string
            $raw = file_get_contents($url);
             
            //Save it to the filepath
            file_put_contents ($filePath, $raw);
        }
         
        //File now definitely exists, create a soap client with it.
        //Uses the browser user agent but this could be set to anything.
        return @new SoapClient($filePath, array('user_agent' => $_SERVER['HTTP_USER_AGENT']));
    }
 
    catch(Exception $e)
    {
        //Something went wrong
        return $e->GetMessage();
    }
}
 
//Returns a single capability as a string
function GetCapability($capability)
{
    try
    {
        //Obtains a SoapClients
        $client = GetSoapClient();
        //Pass the service the parameter you want
        $params = array ('capability' => $capability);
        //Get the capability and then return it
        $result = $client->GetCapability($params);
        return $result->GetCapabilityResult;
    }
    catch(Exception $e)
    {
        //Something went wrong
        return $e->GetMessage();
    }
}
 
//Takes a string array of capabilities and returns them in that order.
//If a capability coudn't be found the service returns null for that element.
function GetCapabilities($capabilities)
{
    try
    {
        //Open SoapClient
        $client = GetSoapClient();
        //Pass parameters
        $params = array ('capabilities' => $capabilities);
        $result = $client->GetCapabilities($params);
 
        //A multidimensional array object is returned.
        //Cast as array.
        $var = (array)$result->GetCapabilitiesResult;
        //Take the 'string' element.
        return $var['string'];
    }
    catch(Exception $e)
    {
        //Something went wrong.
        return $e->GetMessage();
    }
}

These functions create the soap client and stores the WDSL file for later use. They return the given capability (or capabilities) for the browser viewing the sight, although any useragent can be interrogated in the SoapClient constructor. Allowed capabilities are any of the wurfl or .NET names. To use the functions you'll need something like this -  

<html>
 <head>
  <title>Web Service Test</title>
 </head>
<body>
 
 
//Code above
 
echo 'Useragent of device: ';
echo $_SERVER['HTTP_USER_AGENT'];
echo '<p/>';


echo 'Brand name of device: ';
echo GetCapability('brand_name');
echo '<p/>';
 
echo 'Model name of device: ';
echo GetCapability('model_name');
echo '<p/>';
 
$caps = GetCapabilities(array('brand_name', 'model_name'));
echo 'Capabilities as an array: <p/>';
foreach ($caps as $cap)
{
    echo "$cap <br/> ";
}
 
?>
 
 
 </body>
</html>
This will produce this webpage: And that’s it! Your very own piece of cloud. All you need to do is supply a capability to check. There are hundreds that can be used. Here's just a few of them:is_wireless_device (refers to all mobile devices, phones, tablets, portable consoles)
is_tablet
pointing_method (tells you if the input method is a touchscreen or a keypad etc)
device_os (tells you what OS is being, Android, iOS and so on)You can download the PHP code here.

Coming soon, accessing the mobile detection service in Java.

Comments (0)

Author: Products Team

Categories: Development

Tags:

Tom Holmes
>

Products Team

Other posts by Products Team
Contact author

Name:
Email:
Subject:
Message:
x

Tags

.NET 2013 2014 4G 51Degrees 5G A.C.Roma A7 ABI Acer Affiliate Marketing Alcatel Amazon AMP Analysis Analytics Android Android 5.0 Lollipop Android Kitkat Android Lollipop Android Media Stick Apache API Apple Apple TV Archos Asha Asian Market ASP.NET Asus Australia Big Data Black Friday Blackberry Blink Browser C C# Case Study CeBIT CES Chrome Cloud CMS combinations Comparison Competition CoolPad COTW Cron CSS3 Data Data Blog Data File Data Model Daydream Denver Design Desire Eye Desktop Detection Device Device Data Device Detection Device Intelligence Device Popularity Device property Device Types Device Use Display DoCoMo Doogee DotNetNuke Download Drupal Email EReader E-Reader Ericsson Evaluation Event Examples EXPLAY Rio Facebook feature Firefox Firefox OS Fly Foundation Framework France Galaxy S3 Galaxy S5 Galaxy Tab A Galaxy Tab A 8.0 Galaxy Tab A 9.7 Germany Global Google Google Daydream GSMA HAProxy Hardware Hisense HTC HTC ONE MAX HTC OS HTML5 HTTP Huawei HUAWEI. UPDATE HUDL Huwaei IBC Icemobile Prime 4.0 IE IFA IIS Image Optimiser Image Optimizer India Infographic Ingeniux Internet usage iOS iOS 7 iOS 8 ipad iPhone iPhone 6 IsEmailBrowser IsWebApp Italy Japan Java Javascript Jolla Kentico Keynote Kindle Kindle Fire Kindle Fire HD Leagoo Lenovo LG Location Log File Analysis LTE Lumia Map Memory Meta Data Mi 4S Micromax Microsoft Miia Style Mobile Mobile Analysis Mobile Analytics Mobile Devices Mobile Marketing Mixer Module Motorola MVC4 MWC MWC 2017 MWC16 MyPhone Native Native Apps NET New Release News News Letter Nexus Nexus 6 Nexus 9 NFC NGINX Nokia Non-Mobile NVIDIA Omate On7 Opera Opera Mini Operating System Optimisation OS OSX 10.10 OTA Panasonic Patent PC Pebble Performance phablet phone PHP Poland Presentation Press Release Price Band PRIV PS4 Python QMobile QR Codes Redirection Research Reseller Responsive Images RESS Review reviews RIM Ringmark RWD Samsung Scala Screen Screen resolution Screen Size SEO Server Set Box Set Top Box Sharepoint Shark 1 SHIFT phones Sitecore SLUSH Smart TV Smartphone Smartphones Smartwatches Snapdragon Sony Sony Xperia Spain Swedish Beers Symbian Tablet Tablets Tesco Testing Top 5 TOTW TV UDS UK Umbraco Update updates US User Agent UserAgent User-Agent Vendors Version 3 VoLTE VR Wearable Web Web Apps WebKit WebMatrix White Paper Widgets Widnows WiFi Wiko Wileyfox Windows Windows Phone Xbox XBox One Xiaomi Xperia Xperia z Yosemite Z10 ZenFon 2 ZOPO ZTE