Hello,

How to program browser detection in php ?

I would like to detect the browser automatically, then use if browser = ... then ... else if browser = ... then .... endif

How to do so ?

Thanks.

You can use get_browser(): http://php.net/manual/en/function.get-browser.php
But the client can spoof the user agent, so don't trust what you get and always sanitize the data, because an XSS attack can be performed.

Hi, where to place the codes? I would like to place a long codes such as if browser = (IE) then long-IE-php-html-css-codes else if browser = (firefox) then long-firefox-php-html-css-codes.

<?php
function getBrowser() 
{ 
    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $platform = 'Unknown';
    $version= "";

    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';
    }
    elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';
    }
    elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }
    
    // Next get the name of the useragent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'Internet Explorer'; 
        $ub = "MSIE"; 
    } 
    elseif(preg_match('/Firefox/i',$u_agent)) 
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 
    } 
    elseif(preg_match('/Chrome/i',$u_agent)) 
    { 
        $bname = 'Google Chrome'; 
        $ub = "Chrome"; 
    } 
    elseif(preg_match('/Safari/i',$u_agent)) 
    { 
        $bname = 'Apple Safari'; 
        $ub = "Safari"; 
    } 
    elseif(preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 
    } 
    elseif(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 
    } 
    
    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) .
    ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }
    
    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];
        }
        else {
            $version= $matches['version'][1];
        }
    }
    else {
        $version= $matches['version'][0];
    }
    
    // check if we have a number
    if ($version==null || $version=="") {$version="?";}
    
    return array(
        'userAgent' => $u_agent,
        'name'      => $bname,
        'version'   => $version,
        'platform'  => $platform,
        'pattern'    => $pattern
    );
} 

// now try it
$ua=getBrowser();
$yourbrowser= "Your browser: " . $ua['name'] . " " . $ua['version'] . " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
print_r($yourbrowser);
?>

based on the code you posted, all you need to do is to include the file in your php page and perform a simple switch to get the result you are after. something like this:

yourpage.php

include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			echo "you are using chrome";
			break;
		case 'Internet Explorer':
			echo "you are using ie";
			break;
		case 'Mozilla Firefox':
				echo "you are using firefox";
			break;		
		default:
			break;		
	}

now just a reminder that, if you are looking just to change the CSS based on the browser, this is not the way to do it.

Not only change the css, but also change the HTML and php based on the browser. How to do so ?

you can use javascript

navigator.userAgent

Well, what's the complete codes ?

Well, where to place the:

if browser = (IE) then long-IE-php-html-css-codes else if browser = (firefox) then long-firefox-php-html-css-codes ?

The link only shows the Js codes.

you know what you can use @emclodon code, it is much better

<?php

	include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			include('your_google_chrome_page.php'); // your separate google chrome page
			break;
		case 'Internet Explorer':
			include('your_ie_page.php'); // your separate ie page
			break;
		case 'Mozilla Firefox':
			include('your_mozilla_page.php'); //your separate mozilla page
			break;		
		default:	
	}

?>

or you can put condition on every includes

<html>
	<head>
	<?php
	
	include('get_browser.php');
	$browser=getBrowser();

	?>
	
	<?php
	
	switch ($browser['name'])
	{
		case 'Google Chrome':
			echo '<link rel="stylesheet" type="text/css" href="/your_google_chrome_style.css" />';
			echo '<script type="text/javascript" src="/your_google_chrome_javascript.js"></script>';
			break;
		case 'Internet Explorer':
			echo '<link rel="stylesheet" type="text/css" href="/your_ie_style.css" />';
			echo '<script type="text/javascript" src="/your_ie_javascript.js"></script>';
			break;
		case 'Mozilla Firefox':
			echo '<link rel="stylesheet" type="text/css" href="/your_mozilla_style.css" />';
			echo '<script type="text/javascript" src="/your_mozilla_javascript.js"></script>';
		        break;
		default:
	}
	
	?>
	</head>
	<body>
	<?php

	switch ($browser['name'])
	{
		case 'Google Chrome':
			echo '<p>google chrome content</p>';
			break;
		case 'Internet Explorer':
			echo '<p>Internet Explorer content</p>';
			break;
		case 'Mozilla Firefox':
			echo '<p>Mozilla Firefox content</p>';
			break;
		default:
	}
	
	?>
	</body>
	</html>

front-page.php

<?php

	include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			include('Chrome/front-page.php'); // your separate google chrome page
			break;
		case 'Internet Explorer':
			include('IE/front-page.php'); // your separate ie page
			break;
		case 'Mozilla Firefox':
			include('Mozilla/front-page.php'); // your separate mozilla page
			break;		
		default:
			break;		
	}

?>

Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\wordpress\wp-content\themes\ocklaw\IE\front-page.php on line 42

line42: include('Mozilla/front-page.php'); // your separate mozilla page

How to fix it ?

no the error is in front-page.php that inside the IE folder, what is on line 42?

no the error is in front-page.php that inside the IE folder, what is on line 42?

line42: include('Mozilla/front-page.php'); // your separate mozilla page

front-page.php

case 'Google Chrome':
	      include('Chrome/front-page.php'); // your separate google chrome page
		break;
	case 'Internet Explorer':

Parse error: syntax error, unexpected T_STRING in C:\xampp\htdocs\wordpress\wp-content\themes\ocklaw\IE\front-page.php on line 42

line 42: case 'Internet Explorer':

Why is it ?

It's probably an error in Chrome/front-page.php, check your quotes in that file.

What's wrong with the quotes ?

Nothing is missing:

I have this file in each folder:

Chrome : front-page.php
IE : front-page.php
Mozzila : front-page.php

Check inside IE/front-page.php or post that code. The error is there.

IE/front-page.php

<?php get_header(); ?>

<html>
<body>
<div id="example"></div>

<script type="text/javascript">

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";

document.getElementById("example").innerHTML=txt;

</script>


<?php 

echo $_SERVER['HTTP_USER_AGENT'];

?>


<?php

	include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			include('your_google_chrome_page.php'); // your separate google chrome page
			break;
		case 'Internet Explorer':
			include('your_ie_page.php'); // your separate ie page
			break;
		case 'Mozilla Firefox':
			include('your_mozilla_page.php'); your separate mozilla page
			break;		
		default:
			break;		
	}

?>
	

<div id="body">
<div id="bannerContainer">
<div id="banner"></div> 
        <div id="containerSide">
        <div id="slideshow">
          <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/banner1.png">
          <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/banner2.png">
          <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/banner3.png">              
        </div>
        </div>        
</div>

<div id="content">
	<div id="main-front">
	<div id="main">
	<h4>LATEST NEWS</h4>
 		<div class="post">	
    
    <?php query_posts('posts_per_page=3'); ?>
        
	<?php if (have_posts()) : ?>
		<?php while (have_posts()) : the_post(); ?>
        
<p style="border-bottom: 2px dotted #FF0000; width: 650px;"></p><br />        
                      
            <img src="<?php echo get_stylesheet_directory_uri(); ?>/images/pic1.png" ALT="picture1" ALIGN=LEFT><div id="ptitle"><?php the_title(); ?><font color="black"> - <?php the_time('d'); ?>&nbsp<?php the_time('M'); ?>&nbsp<?php the_time('Y'); ?></font></div>
            
            <p><?php the_content(''); ?>... <a href="#">read more ></a></p>
         
      	
     <?php endwhile; ?>
        
<?php endif; ?>
       
  
    </div>
   </div>
   </div>

<div id="side-main">
	<?php get_sidebar(); ?>
 </div>
 
 </div>
</div>

<?php get_footer(); ?>

</body>
</html>

Default case in switch() can't be blank, so or you remove it or you assign an action.

This is not blank ?

switch ($browser)

I'm referring to line 45 and 46, if this is empty then you get an error, if you define a default case you have also to insert some code:

default:
echo 'default case'; # example
break;

bye :)

@cereal: Where do you base this on? Switch with empty default executes fine on my system.

commented: you're right, my mistake +8

front-page.php

<?php

	include('get_browser.php');
	$browser=getBrowser();
	switch ($browser['name'])
	{
		case 'Google Chrome':
			include('Chrome/front_page.php'); // your separate google chrome page
			break;
		case 'Internet Explorer':
			include('IE/front_page.php'); // your separate ie page
			break;
		case 'Mozilla Firefox':
			include('Mozilla/front_page.php'); //your separate mozilla page
			break;		
		default:echo 
		'default case'; # example
		break;			
	}

?>

Warning: include(IE/front_page.php) [function.include]: failed to open stream: No such file or directory in C:\xampp\htdocs\wordpress\wp-content\themes\ocklaw\front-page.php on line 40

Warning: include() [function.include]: Failed opening 'IE/front_page.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\wordpress\wp-content\themes\ocklaw\front-page.php on line 40

mate, It would be easy if you let us know what you are trying to do, and also if you could share the whole source, it would be easy to point out what's kicking your boots away.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.