×


Detect Mobile Devices in PHP

In this article, 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.





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.

Detect Mobile Device

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');
}
?>




Related Articles

Remove duplicates from array PHP
jquery sticky header on scroll
Convert text to speech using PHP
Bootstrap modal popup example on page load
PHP Web Scraping
Ajax live data search using jQuery PHP MySQL
Fetch data from database in PHP and display
How to insert image in database using PHP
How to display PDF file in PHP from database
How to read CSV file in PHP and store in MySQL
Create And Download Word Document in PHP
PHP SplFileObject Standard Library
Preventing Cross Site Request Forgeries(CSRF) in PHP
PHP code to send email using SMTP
Simple pagination in PHP
Simple PHP File Cache
PHP Connection and File Handling on FTP Server
Sending form data to an email using PHP
Recover forgot password using PHP and MySQL




Read more articles


General Knowledge



Learn Popular Language