Php switch for multilingual websites issue - php

I have a problem with multilingual websites... I made some code for my site, and asked a friend for opinion, and he said that server will be much slower when more people are on my domain. He said that I should use Yii or some other framework.. But I'm not familiar with frameworks. :S
So here's my code in config.php
if(isSet($_GET['lang'])){
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else if(isSet($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if(isSet($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$lang = 'hr';
}
switch ($lang) {
case 'en':
$naslovnica_naslov = 'Home';
$onama_naslov = 'About us';
$restoran_naslov = 'Restaurant';
$motel_naslov = 'Motel';
$opcenito_naslov = 'General';
$galerija_naslov = 'Gallery';
$novosti_naslov = 'News & Offers';
$rezervacije_naslov = 'Reservations';
$kontakt_naslov = 'Contact';
$rezervacija_smjestaja = "Reservation of apartment";
$kontakt_informacije = "Contact info";
$kontakt_adrese_h3 = 'Adresses';
$lokacija = 'Location';
$onama_krace = 'Ideal for fun and relaxation, Kiwi Motel is located in the breasts in the town of Gruda. From here, guests can enjoy easy access to all that the lively city has to offer ...';
$vidi_vise = 'See more...';
$svecanosti = 'Ceremonies';
$proslave = '& celebrations';
break;
case 'de':
$naslovnica_naslov = 'Startseite';
$onama_naslov = 'Über uns';
$restoran_naslov = 'Restaurant';
$motel_naslov = 'Motel';
$opcenito_naslov = 'Allgemeine';
$galerija_naslov = 'Galerie';
$novosti_naslov = 'Neuigkeiten & Angeboten';
$rezervacije_naslov = 'Reservierungen';
$kontakt_naslov = 'Kontakt';
$rezervacija_smjestaja = 'Reservierung der Unterkunft';
$kontakt_informacije = 'Kontaktinfos';
$kontakt_adrese_h3 = 'Adressen';
$lokacija = 'Stelle';
$onama_krace = 'Ideal für Spaß und Entspannung, ist Kiwi Motel in der Nähe von Stadt Grude entfernt. Von hier aus können die Gäste einen einfachen Zugang zu allem, was die lebhafte Stadt zu bieten hat ...';
$vidi_vise = 'Mehr sehen...';
$svecanosti = 'Zeremonien';
$proslave = '& Feierlichkeiten';
break;
default:
$naslovnica_naslov = 'Naslovnica';
$onama_naslov = 'O nama';
$restoran_naslov = 'Restoran';
$motel_naslov = 'Motel';
$opcenito_naslov = 'Općenito';
$galerija_naslov = 'Galerija';
$novosti_naslov = 'Novosti & ponude';
$rezervacije_naslov = 'Rezervacije';
$kontakt_naslov = 'Kontakt';
$rezervacija_smjestaja = 'Rezervacija smještaja';
$kontakt_informacije = 'Kontakt informacije';
$kontakt_adrese_h3 = 'Adrese';
$lokacija = 'Lokacija';
$onama_krace = 'Idealan za zabavu i opuštanje, Motel Kiwi smješten u Grude u području grada Grude. S ovog mjesta, gosti mogu imati lagan pristup svemu što ovaj ljupki grad može ponuditi...';
$vidi_vise = 'Vidi više...';
$svecanosti = 'Svečanosti';
$proslave = '& proslave';
}
And I implement this variables after in index.php, contact.php.. So, is there any better solution? Please help!!!

Apart from agreeding with your friend about his suggest (Yii, Laravel, Symfony, Codeigniter, etc..), you can create something like this.
After this part in your config.php:
if(isSet($_GET['lang'])){
$lang = $_GET['lang'];
// register the session and set the cookie
$_SESSION['lang'] = $lang;
setcookie("lang", $lang, time() + (3600 * 24 * 30));
} else if(isSet($_SESSION['lang'])) {
$lang = $_SESSION['lang'];
} else if(isSet($_COOKIE['lang'])) {
$lang = $_COOKIE['lang'];
} else {
$lang = 'hr';
}
insert
$langArray = require 'lang/'.$lang.'.php';
and take off of everything following.
Then create a dir where you will create your language files, for example "lang".
Then, for every language file, you create the file needed in that dir and copy the related part took off from config.php. For example..
//lang/it.php
<?php
return array(
'name' => 'Paolo',
...
);
then another lang file
//lang/en.php
<?php
return array(
'name' => 'Paul',
...
);

i think gettext is better
http://us3.php.net/gettext
but the php extension is very bad, however there are lots of gettext classes for php. just search on github :D
yii, the framework u mentioned, has a good gettext parser

it is a very bad practice to store them directly in a file. You'd better to store them in your database with a column named "lang", then
you can set if
switch($lang) { case "en" : get_data($lang); break;}
Where get_data is a functional exclusively built for your purpose, and argument $lang is a value (en, de, fr etc) which stands for WHERE clause of mySQL query.

Related

PHP how can I store an array globally and query it in functions

I have an array, I want to store it once, it never needs to change.
I want to have different functions for retrieving this information. I tried using a class but PHP doesn't let you store an array and values as an attribute you can just use. This is such a simple task, either I'm missing something or PHP can't do what I imagine is a simple task.
<?php
$questions = array();
$questions[0]['question'] = "How many legs does a spider have?";
$questions[0]['correct_answer'] = "8";
$questions[0]['answer'][0] = "8";
$questions[0]['answer'][1] = "7";
$questions[0]['answer'][2] = "6";
$questions[0]['answer'][3] = "5";
$questions[0]['answer'][4] = "4";
$questions[0]['answer'][5] = "3";
$questions[0]['answer'][6] = "2";
$questions[0]['answer'][7] = "1";
$questions[0]['answer'][8] = "0";
//Questions number 2
$questions[1]['question'] = "What do you put in a Hamburger bun?";
$questions[1]['correct_answer'] = "Hamburger";
$questions[1]['answer'][0] = "Lemons";
$questions[1]['answer'][1] = "Dog food";
$questions[1]['answer'][2] = "Pancakes";
$questions[1]['answer'][3] = "Hamburger";
$questions[1]['answer'][4] = "Flies";
$questions[1]['answer'][5] = "Mormons";
$questions[1]['answer'][6] = "H.P Lovecraft";
$questions[1]['answer'][7] = "A Space Man";
$questions[1]['answer'][8] = "Soup";
//Questions number 3
$questions[2]['question'] = "What is Obama's first name?";
$questions[2]['correct_answer'] = "Barack";
$questions[2]['answer'][0] = "Ludwig";
$questions[2]['answer'][1] = "Homer";
$questions[2]['answer'][2] = "Icarus";
$questions[2]['answer'][3] = "Mcenzie";
$questions[2]['answer'][4] = "Barack";
$questions[2]['answer'][5] = "David";
$questions[2]['answer'][6] = "Donald";
$questions[2]['answer'][7] = "Stewart";
$questions[2]['answer'][8] = "Lewis";
//Questions number 4
$questions[3]['question'] = "How long is a netflix trial?";
$questions[3]['correct_answer'] = "One Month";
$questions[3]['answer'][0] = "Eighteen Days";
$questions[3]['answer'][1] = "Two Weeks";
$questions[3]['answer'][2] = "One Year";
$questions[3]['answer'][3] = "Six Months";
$questions[3]['answer'][4] = "One Month";
$questions[3]['answer'][5] = "Ninty Days";
$questions[3]['answer'][6] = "One Day";
$questions[3]['answer'][7] = "12 Years";
$questions[3]['answer'][8] = "3 Lunar months";
function get_question_by_id($id){
return $questions[$id];
}
?>
question_by_id should get the question the correct answer and all the possible answers of $questions[$id].
You need to get the $questions from the global scope first befor accessing them. Change your function to
function get_question_by_id($id){
global $questions;
return $questions[$id];
}
Or
function get_question_by_id($id, $questions){
return $questions[$id];
}
// You then have to call it like this:
$question = get_question_by_id($id, $questions);
I just declared it in a separate function and called get_questions I can call us the in_array function to search the return value. Post it as an answer and I'll close it off, Getters and setters :) KISS method

PHP Suggest Jobs within Location set by user field

Got a strange problem here on my little project, I have an account area that people can set a location so we can suggest job openings within the area they live in.
EDIT: Code indented - Sorry
The locations that do not work are "Maidstone" & "Medway". These locations are all stored in the database, When another user adds a job they can set the location the job is in and that will then add that job to the database under "State" String.
Other Locations such as Canterbury do work and the jobs that are listed under the Canterbury location show up on the users account as they should.
This php works for every location other then 2 of them which is really strange.
<?php
class SJB_Classifieds_SuggestedJobs extends SJB_Function
{
public function execute()
{
$tp = SJB_System::getTemplateProcessor();
$count_listing = SJB_Request::getVar('count_listing', 10, null, 'int');
$current_user = SJB_UserManager::getCurrentUser();
$properties = $current_user->getProperties();
foreach ($properties as $property) {
if ($property->getType() == 'location') {
$fields = $property->type->child;
$childProperties = $fields->getProperties();
foreach ($childProperties as $childProperty) {
if (in_array($childProperty->getID(), array('State'))) {
$value = $childProperty->getValue();
switch ($childProperty->getType()) {
case 'list':
if ($childProperty->getID() == 'State') {
$displayAS = $childProperty->display_as;
$displayAS = $displayAS?$displayAS:'State';
$listValues = SJB_StatesManager::getStatesNamesByCountry(false, true, $displayAS);
}
else
$listValues = $childProperty->type->list_values;
foreach ($listValues as $values) {
if ($value == $values['id'])
$phrase[strtolower($childProperty->getID())] = $values['caption'];
}
break;
default:
$phrase[strtolower($childProperty->getID())] = $value;
break;
}
}
}
}
}
$phrase = array_diff($phrase, array(''));
$phrase = implode(" ", $phrase);
$listing_type_id = "Job";
$request['action'] = 'search';
$request['listing_type']['equal'] = $listing_type_id;
$request['default_listings_per_page'] = $count_listing;
$request['default_sorting_field'] = "activation_date";
$request['default_sorting_order'] = "DESC";
$request['keywords']['relevance'] = $phrase;
$searchResultsTP = new SJB_SearchResultsTP($request, $listing_type_id, array('field'=>'keywords', 'value'=>$phrase));
$tp = $searchResultsTP->getChargedTemplateProcessor();
$tp->display('suggested_jobs.tpl');
}
}
Not sure if my problem is due to the PHP that tells which jobs to display.
Could someone just skip though the PHP and let me know if anythings wrong? I really want to work this out on my own however I'm alittle lost and if i can find out that the PHP is fine then I can figure it out some where else :)
Thanks!

How to request MYSQL elements instead of using Array in PHP

I made language php code which working fine. I request the translations from different like en.php, de.php.
In en.php i have one array:
$language = Array('homepage' => 'Site Home','contact' => 'Contact Us');
I use $_SESSION for get the language en, de, hu and the others. I get the language files with this code:
$sql = mysql_query("SELECT * FROM languages ORDER BY langID");
$count = mysql_num_rows($sql);
if ($count) {
while ($ds = mysql_fetch_array($sql)) {
switch ($_SESSION['language']) {
case $ds['tag']:
include_once('language/' . $ds['tag'] . '.php');
break;
default:
include_once('language/en.php');
break;
}
}
}
But I would like to change array for mysql database. In my DB i have a table with:
translatesID
tag(its now the 'en' or can be other like 'de')
key(what i want to be the array like 'homepage')
value(which would be the 'Site Home')
In index.php I get the 'Site Home' with the following php code:
<?php echo $language['homepage']; ?>
My question is which Mysql request or PHP code can solve my request?
Problem solved with this code:
$language = array();
$sql = mysql_query("SELECT * FROM translates WHERE '" . $_SESSION['language'] . "' = tag");
while($row = mysql_fetch_array($sql)) {
$language[$row['key']] = $row['value'];
}

PHP How to replace specific string from an URL

I'm bulding a multilanguage web in PHP, i have the class for the language change, i can do it by setting the $_SESSION or just by changing the lang value in the url, i'm working with rewrite mod for apache so this is how my URL looks like:
http://www.server.com/en/something/else/to/do
I have a function that displays an upper bar in the entire site, and in that bar i have the flags for language change.
I use this class to change Language:
class IDIOMAS {
private $UserLng;
private $langSelected;
public $lang = array();
public function __construct($userLanguage){
$this->UserLng = $userLanguage;
}
public function userLanguage(){
switch($this->UserLng){
case "en":
$lang['PAGE_TITLE'] = TITULO().' | Breaking news, World news, Opinion';
// Menu
$lang['MENU_LOGIN'] = 'Login';
$lang['MENU_SIGNUP'] = 'Sign up';
$lang['MENU_LOGOUT'] = 'Logout';
$lang['MENU_SEARCH'] = 'Search';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Thank you, we'll let you know when we become online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'This e-mail is already registered';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'The e-mail you entered is invalid';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'You must write down your e-mail';
$lang['SUBSCRIBE_TITLE'] = '¡Subscribe!';
$lang['SUBSCRIBE_CONTENT'] = 'And be the first to read the best articles in the web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Enter your E-mail';
$lang['SUBSCRIBE_SEND'] = 'SEND';
//LOGIN
$lang['LOGIN_TITLE'] = 'Please Login to your account';
$lang['LOGIN_USER'] = 'User';
$lang['LOGIN_PASSWORD'] = 'Password';
$lang['LOGIN_ERROR'] = '¡User and/or password invalid!';
//REGISTER
$lang['REGISTER_NAME'] = 'Please write your name';
$lang['REGISTER_LAST_NAME'] = 'Please write your last name';
$lang['REGISTER_EMAIL'] = 'Write your E-mail';
$lang['REGISTER_CITY'] = 'Enter your City name';
$lang['REGISTER_COUNTRY'] = '¿Where are you from?';
$lang['REGISTER_ZIP_CODE'] = 'Enter your ZIP Code';
$lang['REGISTER_DATE_BIRTH'] = 'Please enter your date of birth';
return $lang;
break;
case "es":
$lang['PAGE_TITLE'] = TITULO().' | Noticias de última hora, Noticias mundiales, Matrices de opinión';
// Menu
$lang['MENU_LOGIN'] = 'Entrar';
$lang['MENU_SIGNUP'] = 'Registrarse';
$lang['MENU_LOGOUT'] = 'Salir';
$lang['MENU_SEARCH'] = 'Buscar';
//Suscripciones
$lang['SUBSCRIBE_SUCCESS'] = "¡Gracias, te avisaremos cuando estemos online!";
$lang['SUBSCRIBE_EMAIL_REGISTERED'] = 'Este email ya se encuentra registrado';
$lang['SUBSCRIBE_EMAIL_INVALID'] = 'El correo que introdujiste es inválido';
$lang['SUBSCRIBE_EMAIL_WRITE'] = 'Debes escribir tu email';
$lang['SUBSCRIBE_TITLE'] = '¡Suscríbete!';
$lang['SUBSCRIBE_CONTENT'] = 'Y se el primero en leer las mejores noticias y artículos en la web';
$lang['SUBSCRIBE_PLACEHOLDER'] = 'Introduce tu E-mail';
$lang['SUBSCRIBE_SEND'] = 'Enviar';
//LOGIN
$lang['LOGIN_TITLE'] = 'Por favor inicia sesión en tu cuenta';
$lang['LOGIN_USER'] = 'Usuario';
$lang['LOGIN_PASSWORD'] = 'Clave';
$lang['LOGIN_ERROR'] = '¡Usuario y/o clave incorrectos!';
//REGISTRO
$lang['REGISTRO_NOMBRE'] = 'Por favor introduce tu nombre';
$lang['REGISTRO_APELLIDO'] = 'Por favor introduce tu apellido';
$lang['REGISTRO_CORREO'] = 'Introduce tu correo electrónico';
$lang['REGISTRO_CIUDAD'] = 'Introduce el nombre de tu ciudad';
$lang['REGISTRO_PAIS'] = '¿De donde eres?';
$lang['REGISTRO_CODIGO_POSTAL'] = 'Introduce tu Código Postal';
$lang['REGISTRO_FECHA_NAC'] = 'Por favor introduce tu fecha de nacimiento';
return $lang;
break;
}
}
}
I use this class with this code:
$language = new IDIOMAS($lang);
$langArray = array();
$langArray = $language->userLanguage();
And set the language like this:
if (!isset($_SESSION['idioma'])){
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$_SESSION['idioma'] = $lang;
}else{
$lang = $_SESSION['idioma'];
}
if(isset($_GET['lang']) && in_array($_GET['lang'], array('en', 'es'))){
$_SESSION['idioma'] = $_GET['lang'];
$lang = $_SESSION['idioma'];
}
Now the issue i have is that when i try to change language of the page i'm on, i mean, if i'm located in www.server.com and nothing else i need to put the /es or /en at the end for changing the lang, but if i'm in www.server.com/es/something/else/to/do i need to change specificallly the /es parameter.
I have a function to get the current url for redirections when being logged or register.
function getUrl() {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
return $url;
}
I was trying to change the lang value inside that function with no success,
Really appreciate any help
Here is a simple solution that I would do. I don't know if its exactly what you'll want to use:
// Find the first forward slash location
$pos1 = strpos($url,'/'); // The whole URL
// You only need this next line if your language codes are different sizes
// If they are always 2 then can alter the code to not use it
$pos2 = strpos($url,'/',$pos1); // Now find the second by offsetting
$base = substr($url,0,$pos1); // Get domain name half
$end = substr($url,$pos2); // Get everything after language area
// Now from the function return the result
$val = $base.'/'.$newlang.'/'.$end;
return $val;
You may need to add or subtract 1 on the $pos to get the right values returned, like so:
$pos2 = strpos($url,'/',$pos1+1); // In case its finding the wrong slash
$base = substr($url,0,$pos1-1); // In case its returning the slash
$end = substr($url,$pos2+1); // In case its return the slash
Please tweak and test this, it is only the concept in action, I have not tested this snip-it.
Finally i got it by modifying the getUrl function to this:
function getUrl($newlang) {
$url = #( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= $_SERVER["REQUEST_URI"];
$substr = substr($url,27,3);
$base = substr($url,0,28);
$resto = substr($url,31,1000);
$newUrl = $base.$newlang."/".$resto;
return $newUrl;
}
and calling the function like this getUrl("en") or getUrl("es");
Maybe this can be usefull for someone else.

Using the PHP HTTP_ACCEPT_LANGUAGE server variable

I created a PHP script that checks the HTTP_ACCEPT_LANGUAGE and loads the website using the appropriate language from the 1st two characters:
$http_lang = substr($_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2);
switch ($http_lang) {
case 'en':
$SESSION->conf['language'] = 'english';
break;
case 'es':
$SESSION->conf['language'] = 'spanish';
break;
default:
$SESSION->conf['language'] = $PREFS->conf['languages'][$SESSION->conf['language_id']];
}
If I change the language to Spanish in Firefox the website loads in Spanish fine. However I have had several reports that people in Colombia see the website in english.
Details:
"es-co" LCID = 9226 Spanish(Colombia)
Anyone have any ideas as to why this is happening? I thought this was the best way to check what language users support.
A more contemporary method would be to use http_negotiate_language():
$map = array("en" => "english", "es" => "spanish");
$conf_language= $map[ http_negotiate_language(array_keys($map)) ];
If you don't have the http extension installed (and not the intl one as well), there is yet another workaround in the comments (user-note #86787 (Nov 2008; by Anonymous)):
<?php
/*
determine which language out of an available set the user prefers most
$available_languages array with language-tag-strings (must be lowercase) that are available
$http_accept_language a HTTP_ACCEPT_LANGUAGE string (read from $_SERVER['HTTP_ACCEPT_LANGUAGE'] if left out)
*/
function prefered_language ($available_languages,$http_accept_language="auto") {
// if $http_accept_language was left out, read it from the HTTP-Header
if ($http_accept_language == "auto") $http_accept_language = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
// standard for HTTP_ACCEPT_LANGUAGE is defined under
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
// pattern to find is therefore something like this:
// 1#( language-range [ ";" "q" "=" qvalue ] )
// where:
// language-range = ( ( 1*8ALPHA *( "-" 1*8ALPHA ) ) | "*" )
// qvalue = ( "0" [ "." 0*3DIGIT ] )
// | ( "1" [ "." 0*3("0") ] )
preg_match_all("/([[:alpha:]]{1,8})(-([[:alpha:]|-]{1,8}))?" .
"(\s*;\s*q\s*=\s*(1\.0{0,3}|0\.\d{0,3}))?\s*(,|$)/i",
$http_accept_language, $hits, PREG_SET_ORDER);
// default language (in case of no hits) is the first in the array
$bestlang = $available_languages[0];
$bestqval = 0;
foreach ($hits as $arr) {
// read data from the array of this hit
$langprefix = strtolower ($arr[1]);
if (!empty($arr[3])) {
$langrange = strtolower ($arr[3]);
$language = $langprefix . "-" . $langrange;
}
else $language = $langprefix;
$qvalue = 1.0;
if (!empty($arr[5])) $qvalue = floatval($arr[5]);
// find q-maximal language
if (in_array($language,$available_languages) && ($qvalue > $bestqval)) {
$bestlang = $language;
$bestqval = $qvalue;
}
// if no direct hit, try the prefix only but decrease q-value by 10% (as http_negotiate_language does)
else if (in_array($langprefix,$available_languages) && (($qvalue*0.9) > $bestqval)) {
$bestlang = $langprefix;
$bestqval = $qvalue*0.9;
}
}
return $bestlang;
}
?>
I used the regex from #GabrielAnderson and devised this function which behaves according to RFC 2616 (when no quality value is given to a language, it defaults to 1).
When several languages share the same quality value, the most specific are given priority over the less specific ones. (this behaviour is not part of the RFC which provides no recommendation for this specific case)
function Get_Client_Prefered_Language ($getSortedList = false, $acceptedLanguages = false)
{
if (empty($acceptedLanguages))
$acceptedLanguages = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
// regex inspired from #GabrielAnderson on http://stackoverflow.com/questions/6038236/http-accept-language
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})*)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $acceptedLanguages, $lang_parse);
$langs = $lang_parse[1];
$ranks = $lang_parse[4];
// (create an associative array 'language' => 'preference')
$lang2pref = array();
for($i=0; $i<count($langs); $i++)
$lang2pref[$langs[$i]] = (float) (!empty($ranks[$i]) ? $ranks[$i] : 1);
// (comparison function for uksort)
$cmpLangs = function ($a, $b) use ($lang2pref) {
if ($lang2pref[$a] > $lang2pref[$b])
return -1;
elseif ($lang2pref[$a] < $lang2pref[$b])
return 1;
elseif (strlen($a) > strlen($b))
return -1;
elseif (strlen($a) < strlen($b))
return 1;
else
return 0;
};
// sort the languages by prefered language and by the most specific region
uksort($lang2pref, $cmpLangs);
if ($getSortedList)
return $lang2pref;
// return the first value's key
reset($lang2pref);
return key($lang2pref);
}
Example:
print_r(Get_Client_Prefered_Language(true, 'en,en-US,en-AU;q=0.8,fr;q=0.6,en-GB;q=0.4'));
Outputs:
Array
(
[en-US] => 1
[en] => 1
[en-AU] => 0.8
[fr] => 0.6
[en-GB] => 0.4
)
As you can notice, 'en-US' appears in first position despite the fact that 'en' was first in the given string.
So you could use this function and just replace your first line of code by:
$http_lang = substr(Get_Client_Prefered_Language(),0,2);
Do you know if this is happening for all visitors to your site from Colombia? Users are usually free to alter the language settings of their browsers — or to have them altered for them by whoever is in charge of the computer. As zerkms recommends, try logging IP addresses and their headers.
If you have the intl extension installed you can use Locale::lookup and Locale::acceptFromHttp to get a best-fit choice of language from the users browser settings and a list of what translations you have available.
Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']); # e.g. "en_US"
In the end I went with this solution:
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);
if (count($lang_parse[1])){
$langs = array_combine($lang_parse[1], $lang_parse[4]);
foreach ($langs as $lang => $val){
if ($val === '') $langs[$lang] = 1;
}
arsort($langs, SORT_NUMERIC);
}
foreach ($langs as $lang => $val){
if (strpos($lang,'en')===0){
$language = 'english';
break;
} else if (strpos($lang,'es')===0){
$language = 'spanish';
}
}
}
I would like to thank AJ for the links. Also thanks to all that replied.
I will use full locale code to refer language, because like zh-TW and zh-CN is 2 different language.
function httpAcceptLanguage($httpAcceptLanguage = null)
{
if ($httpAcceptLanguage == null) {
$httpAcceptLanguage = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
}
$languages = explode(',', $httpAcceptLanguage);
$result = array();
foreach ($languages as $language) {
$lang = explode(';q=', $language);
// $lang == [language, weight], default weight = 1
$result[$lang[0]] = isset($lang[1]) ? floatval($lang[1]) : 1;
}
arsort($result);
return $result;
}
// zh-TW,en-US;q=0.7,en;q=0.3
echo $_SERVER['HTTP_ACCEPT_LANGUAGE'];
/*
Array
(
[zh-TW] => 1
[en-US] => 0.7
[en] => 0.3
)
*/
print_r(httpAcceptLanguage());
if you want to store languages in array, i do this:
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', 'pt-br,pt;q=0.8,en-us;q=0.5,en,en-uk;q=0.3', $lang_parse);
$langs = $lang_parse[1];
$rank = $lang_parse[4];
for($i=0; $i<count($langs); $i++){
if ($rank[$i] == NULL) $rank[$i] = $rank[$i+1];
}
this output an array to languages e other with values
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', 'pt-br,pt;q=0.8,en-us;q=0.5,en,en-uk;q=0.3', $lang_parse);
$langs = $lang_parse[1];
$rank = $lang_parse[4];
$lang = array();
for($i=0; $i<count($langs); $i++){
$lang[$langs[$i]] = ($rank[$i] == NULL) ? $rank[$i+1] : $rank[$i];
}
this output an array like this:
Array
(
[pt-br] => 0.8
[pt] => 0.8
[en-us] => 0.5
[en] => 0.3
[en-uk] => 0.3
)
I put my trust in the skilled programmers who work for PHP and think ahead.
Here is my version of a label for the Google translator drop down.
function gethttplanguage(){
$langs = array(
'en',// default
'it',
'dn',
'fr',
'es'
);
$questions = array(
"en" => "If you wish to see this site in another language click here",
"it" => "Se vuole vedere questo sito in italiano clicca qui",
"dn" => "Hvis du ønsker at se denne hjemmeside i danske klik her",
"fr" => "Si vous voulez visualiser ce site en français, cliquez ici",
"es" => "Si quieres ver este sitio en español haga clic aquí"
);
$result = array();
http_negotiate_language($langs, &$result);
return $questions[key($result)];
}

Categories