Dave's Brain

Browse - programming tips - browser detection in perl cgi

Date: 2008apr11
Level: Beginner
Language: perl

Q.  On a server-side CGI script how I detect which browser the user is
running?

A.  

Please note that its best to use feature detection rather than browser
detection.  Maybe the next version of IE will have that feature
you assume it doesn't have.

Here are some simple perl code that sees what browser the user is running:

sub isFirefox()
{
        return $ENV{HTTP_USER_AGENT} =~ m/Firefox/;
}

sub isIE()
{
        return $ENV{HTTP_USER_AGENT} =~ m/MSIE/;
}

# Use like this...
sub main()
{
	print "Content-Type: text/plain\n\n";

	if (isFirefox())
	{
		print "You seem to be using Firefox\n";
	}
	elsif (isIE())
	{
		print "You seem to be using Microsoft Internet Explorer\n";
	}
	else
	{
		print "You're not using Firefox or MSIE\n";
	}
}

main();

Add a comment

Sign in to add a comment
Copyright © 2008, dave - Code on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License.