PHP – Detect mobile device and do redirection

We can use PHP to detect the browser user agent such that it would redirect user to another URL if the request comes from a mobile device.

1. Create the user_agent.php.

<?php
$iphone  = strpos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$android = strpos($_SERVER['HTTP_USER_AGENT'],"Android");
$palmpre = strpos($_SERVER['HTTP_USER_AGENT'],"webOS");
$berry   = strpos($_SERVER['HTTP_USER_AGENT'],"BlackBerry");
$ipod    = strpos($_SERVER['HTTP_USER_AGENT'],"iPod");

if ($iphone || $android || $palmpre || $ipod || $berry == true) { 
  header('Location: http://eureka.ykyuen.info');
  //OR
  echo "<script>window.location='http://eureka.ykyuen.info'</script>";
}
?>

 

Include the user_agent.php inside those views PHP where you want to redirect the visitor if they use a mobile.

<?php include('user_agent.php'); ?>
<!-- HTML below-->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body></body>
</html>

 

Done =)

Reference: 9Lessons – Redirect Mobile Devices with PHP

Advertisements

3 thoughts on “PHP – Detect mobile device and do redirection”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s