Function code that USES php to determine the type and language of the browser

  • 2020-05-30 19:45:06
  • OfStack

We often see websites that show the type of browser you are using and the language you are using. For example, the browser you are using is IE6, traditional Chinese. Does it look fancy?

In fact, such a function is not difficult to achieve, is nothing more than to judge the browser type and language, if JS to do it should be very simple, here we see how to use PHP to achieve such a function, since it is to make a judgment, you can use PHP conditional statement if.. else to judge the implementation.

Determine the browser type:

< ?php echo $_SERVER["HTTP_USER_AGENT"]; ? >

Determine browser language:

< ?php echo $_SERVER["HTTP_ACCEPT_LANGUAGE"]; ? >

The specific procedures to determine the browser type are as follows:

if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 8.0"))  
echo "Internet Explorer 8.0";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 7.0"))  
echo "Internet Explorer 7.0";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"MSIE 6.0"))  
echo "Internet Explorer 6.0";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox/3"))  
echo "Firefox 3";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"Firefox/2"))  
echo "Firefox 2";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"Chrome"))  
echo "Google Chrome";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"Safari"))  
echo "Safari";  
else if(strpos($_SERVER["HTTP_USER_AGENT"],"Opera"))  
echo "Opera";  
else echo $_SERVER["HTTP_USER_AGENT"];  

The specific procedures to judge the browser language are as follows:

$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 4); // Only take before 4 Bit, so only the most priority language is judged. If you take before 5 Bit, maybe en,zh The situation affects the judgment.   
if (preg_match("/zh-c/i", $lang))  
echo " Simplified Chinese ";  
else if (preg_match("/zh/i", $lang))  
echo " Numerous � Chinese ";  
else if (preg_match("/en/i", $lang))  
echo "English";  
else if (preg_match("/fr/i", $lang))  
echo "French";  
else if (preg_match("/de/i", $lang))  
echo "German";  
else if (preg_match("/jp/i", $lang))  
echo "Japanese";  
else if (preg_match("/ko/i", $lang))  
echo "Korean";  
else if (preg_match("/es/i", $lang))  
echo "Spanish";  
else if (preg_match("/sv/i", $lang))  
echo "Swedish";  

Summary: the browser type is determined by analyzing the content of _SERVER["HTTP_USER_AGENT"], while the browser language is analyzed by _SERVER["HTTP_ACCEPT_LANGUAGE"].

Principle: because the browser always sends some content containing its own information (browser type, language) when connecting with the server. So here we mainly analyze _SERVER["HTTP_USER_AGENT"](browser type) and _SERVER["HTTP_ACCEPT_LANGUAGE"](browser language). All we have to do is read it out and then compare it with the strpos or preg_match functions. We can also make the page more beautiful according to the design of the program.

Related articles: