Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

Checking browser's language by 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.

I tried the following code unsuccessfully

<?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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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.

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

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...