Redirecting Mobile Browsers to Mobile Optimized Site

You want to send mobile or tablet browsers to an alternative site or alternative content that is optimized for their device

Posted on March 2, 2016 in PHP

The get_browser() function examines the environment variable ( set by the web server) and compares it to browsers listed in an external browser capability file. Due to licensing issues, PHP isn’t distributed with a browser capability file. One source for a browser capability file is Browscap (http://browscap.org/). Download the php_browscap.ini file from that site.

Once you download a browser capability file, you need to tell PHP where to find it by setting the browscap configuration directive to the pathname of the file. If you use PHP as CGI, set the directive in the php.ini file:


browscap=/usr/local/lib/php_browscap.ini

After you identify the device as mobile, you can then redirect the request to a specific mobile optimized site or render a mobile optimized page:


header('Location: http://m.example.com'/);

As a lighter-weight alternative to get_browser(), parse the $_SERVER[‘HTTP_USER_AGENT’] your self.

Use the object returned by get_browser() to determine if it’s a mobile browser:


if ($browser->ismobilebrowser) {
    //print mobile layout
}
else{
    //print desktop layout
}


comments powered by Disqus