Q:

How to detect a mobile device using PHP?

belongs to collection: PHP Programming Exercises

0

Detect Mobile Devices in PHP

How to detect a mobile device using PHP

In this exercise, you will learn a simple PHP code snippet to detect mobile devices.

These days, every organisation wants to make their websites responsive. But what if your website is too old, or you want to make a different version of the same website for different devices? To provide a better display experience, we need to detect the browser of our users. It is the best way to detect devices on the server side and prevent them from loading unnecessary content. The mobile version of the website will be available on the mobile device and the desktop version will be available on the desktop device.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

HTTP_USER_AGENT

HTTP_USER_AGENT is a string denoting the user agent that is accessing the page. The website includes a user agent field in its header while connecting to a browser. By using HTTP_USER_AGENT, we can easily detect the device name.

Syntax of HTTP_USER_AGENT

$_SERVER['HTTP_USER_AGENT']

Here, $_SERVER is a special reserved PHP super global variable that holds all web server information about headers, paths, and script locations. These special variables were introduced in PHP 4.1.0.

In the given code snippet, we can easily detect the device name on which our website is opened.

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

if ($iphone || $android || $webos || $ipod || $blkberry == true)
{
   header('Location: example.com');
}
else {
   header('Location:etutorialspoint.com');
}
?>

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP Programming Exercises

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to send HTML form data to email using PHP?... >>
<< How does PHP store data in cache?...