通过 PHP 检查浏览器的语言? [英] Checking browser's language by PHP?

查看:33
本文介绍了通过 PHP 检查浏览器的语言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过 PHP 检查用户浏览器的语言?

How can I check the language of user's browser by PHP?

我需要为美国和英国的用户显示不同的页面.

I need to show a different page for people in US and in UK.

我尝试了以下代码失败

<?php
if(ereg("us", $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
   include('http://page.com/us.txt');
else
   include('http://page.com/uk.txt');
?>

我为美国和英国的人们运行了一个特定的代码.

I run a specific code for people in US and for them in UK.

推荐答案

可能只是区分大小写的问题;eregi('en-us') 或 preg_match('/en-us/i') 应该已经找到了.

Likely just a case sensitivity issue; eregi('en-us') or preg_match('/en-us/i') should have picked it up.

但是,有时仅在标题中查找en-us"可能会出错,尤其是当同时列出美国和英国语言时.Accept-Language"实际上是一个相当复杂的标题,您确实需要一个合适的解析器.

However, just looking for ‘en-us’ in the header may get it wrong sometimes, in particular when both the US and UK languages are listed. "Accept-Language" is actually quite a complicated header, which really you'd want a proper parser for.

如果你有 PECL,整个工作已经为你完成:http://www.php.net/manual/en/function.http-negotiate-language.php

If you have PECL the whole job is already done for you: http://www.php.net/manual/en/function.http-negotiate-language.php

我不知道为什么其他答案都用于 User-Agent 标头;这完全是假的.User-Agent 没有被强制要求在任何特定的地方保存语言值,对于某些浏览器(例如 Opera 和一些我从未听说过的名为Internet Explorer"的小浏览器),它根本不会.它确实包含一种语言,这将是浏览器构建所使用的语言,而不是您应该查看的用户首选语言.(此设置将默认为构建语言,但用户可以通过首选项 UI 进行自定义.)

I don't know why the other answers are going for the User-Agent header; this is utterly bogus. User-Agent is not mandated to hold a language value in any particular place, and for some browsers (eg. Opera, and some minor browser I've never heard of called ‘Internet Explorer’) it will not at all. Where it does contain a language, that'll be the of language the browser build was installed in, not the user's preferred language which is what you should be looking at. (This setting will default to the build language, but can be customised by the user from the preferences UI.)

这篇关于通过 PHP 检查浏览器的语言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆