Write a PHP script for Browser Detection

By Shahnail Khan Last updated : December 16, 2023

Problem statement

Write a simple PHP script to detect the user's browser and output the User-Agent information.

Prerequisites

To understand this solution better, you should have the basic knowledge of the following PHP topics:

Displaying the browser information using PHP

For displaying the browser information, we use the $_SERVER superglobal variable in PHP.

PHP $_SERVER is an array that contains the server-related information like headers, paths, and script locations, a web server entry this information in this array that is accessible through the $_SERVER variable.

The general syntax for accessing elements within the $_SERVER superglobal array in PHP is:

$_SERVER['key'];

For this problem, the value of the key is HTTP_USER_AGENT. It retrieves the User-Agent string from the request headers.

PHP script for Browser Detection

The code given below is used for Browser Detection.

<?php
// Get the User-Agent from the server 
// request headers
$user_agent = $_SERVER["HTTP_USER_AGENT"];

// Display the User-Agent information
echo "Your User-Agent is: $user_agent";
?>

Output

The output of the given code is:

Your User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/98.0.4758.102 Safari/537.36

Code Explanation

  • $_SERVER['HTTP_USER_AGENT'] is a PHP variable that retrieves the User-Agent string from the request headers.
  • The User-Agent string contains details about the user's browser and operating system.
  • We then use echo to show this User-Agent information on the webpage.

More PHP Programs »

All PHP Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.