How to automatically reflect changes when adding PHP cookie? - php

My website by default is in English
But I can change the language, when a visitor visits our website with a url of a news item in Spanish:
example.com/es/news/718/url-title-article/
The url given as an example is a news in Spanish since the first folder or directory is named "es" example.com/es/news/718/url-title-article/ -> es
And, that's where the trick comes, since I have a function that allows me to obtain the name of the first folder or directory and if it matches with the given parameters, it should set a cookie with the language of that url, in this case Spanish -> "es".
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
}
if(isset($_COOKIE['language'])){
if($_COOKIE['language']==='en'){
$WEBSITE_TITLE = " | WebSIte EN";
$LANG = 'en';
$language = "en";
}elseif($_COOKIE['language']==='es'){
$WEBSITE_TITLE = " | WebSite ES";
$LANG = 'es';
$language = "es";
}
} else {
$WEBSITE_TITLE = " | WebSite DEFAULT EN";
$LANG = 'en';
$language = "en";
}
But the problem, is that I have to reload the page to see the changes of the new language added to the site.
So how can you solve it without having to reload the site.

You need to write the logic which determines the language so it doesn't depend on the cookie.
So, before, where you might have had something like:
$language_data = get_i18n_data( $_COOKIES['language'] );
You would instead have something like:
function get_language() {
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
return 'es'
}
return $_COOKIES['language'];
}
$language_data = get_i18n_data( get_language() );

The reason for refresh being needed is that $LANG and $language is set by an existing cookie and not the new one.
Analysing your code:
if($FOLDER_LANG === "es" || $SUBDOMAIN_LANG === "es") {
setcookie ('language', 'es', time()+60*60*24*365, '/', 'example.com');
}
Here, it's setting the cookie only in the header. It is not accessible until the page is reloaded.
One option is to add the following in the if condition:
$LANG = 'es';
$language = "es";
The rest of your code then reads existing cookies so this is what will load on the same page even if the cookie is set just before it:
A better way in my opinion is to keep it simple and expandable by using variable $language to drive the data:
$language = 'en'; //this is default
if(isset($_COOKIE['language'])){
$language = $_COOKIE['language'];
}
//now check if current $language is different to folder
if($FOLDER_LANG != $language || $SUBDOMAIN_LANG != $language) {
//this is condition depends on your variables. You might need && if both conditions should be met or modify as required
//set the language for this page (so no need for refresh and also set the cookie
$language = $FOLDER_LANG ? $FOLDER_LANG : $SUBDOMAIN_LANG; //sets to folder or sudomain language code if $FOLDER_LANG is empty. You can switch the two folders to priotorise the latter.
//now set the cookie
setcookie ('language', $language, time()+60*60*24*365, '/', 'example.com');
}
//now set the the title and the extra variable $LANG (you probably should choose one variable to use)
$WEBSITE_TITLE = " | WebSite . strtoupper($language)";
$LANG = $language;
Now you can support more languages and also won't need to refresh

Related

I can't set a php cookie

I made a php script that allows me to switch the language of my website and for that, I used a cookie called lang to store the user's language prefer but I don't Know why this cookie can't be set as I can't find it in the chrome developer tap .. Although I made this script also with session variable in case cookie isn't set, it doesn't work either, as it shifts the language whenever I change the page
this is my PHP script
<?php
session_start();
if(isset($_GET['lang'])) {
$lan = $_GET['lang'];
$_SESSION['lang'] = $lan;
setcookie("lang", $lan, time() + (3600 * 24 * 30), '/');
} else if (isset($_SESSION['lang'])) {
$lan = $_SESSION['lang'];
} else if (isset($_COOKIE['lang'])) {
$lan = $_COOKIE['lang'];
} else {
$lan = 'en';
}
include "languages/" . $lan . ".php";
?>
I have two files in that language folder en.php and ar.php and each one contains an array with translation like below
<?php
$lang = array(
"Give" => "Give",
"Blood" => "Blood",
"Register as a donator" => "Register as a donator",
"Search for a donator" => "Search for a donator"
I include my script in all my site's pages
here is my chrome developer tap screen shot
any thoughts?
Thanks for helping in advance :)

PHP Check Url and print default parameters

I Have Url structure for multi language system like this:
for default language ie: en (not show/detect short language in url)
localhost/cms
localhost/cms/article/slug/etc...
And Another Language Like:
localhost/cms/fr
localhost/cms/fr/article/slug/etc...
My Idea:
define a list of available languages for My app,
define a default language I use when,
a. there is no language provided (localhost/cms/users),
b. the provided language is unknown (localhost/cms/fr/users).
in my code, get the current Language (ex: en) and the routableURI,
a URI without any language in it (ex: cms/users)
I have This code:
function urlss(){
$uri = $_SERVER['REQUEST_URI'];
$languages = ['en', 'fr', 'es', 'de'];
// this is my default language
$defaultLang = 'en';
// $currentLang is the language I'll use to show the contents
$currentLang = $defaultLang;
$uri = ltrim(rawurldecode($uri), '/');
$parts = explode('/', $uri);
if( ! empty($parts) && in_array(strtolower($parts[0]), $languages)) {
$currentLang = array_shift($parts);
}
$routableUri = implode('/', $parts);
return $routableUri;
}
My code output default language: (false Output)and not worked
check: localhost/cms/ Or localhost/cms/users/
Output is: cms/ Or cms/users/
Output for another language: (true Output)worked true
check: localhost/cms/fr/ Output is cms/fr/ Or localhost/cms/fr/users/Output is : cms/fr/users/
How do can i print my default language, without add/detect short language name in url like this?!
Check: localhost/cms Output Is:cms/en Or Check localhost/cms/users/ Output Is: cms/en/users/.

Language based on HTTP_ACCEPT_LANGUAGE and database languages

I have a web site made in 3 languages, but will (maybe) be expanded.
So I created a table on the database where I insert the languages of the Website.
As index.php I have a script. If the URI detected is "/" the script redirects to /language/index.php.
I'd like now to have a script which dinamically redirects based on HTTP_ACCEPT_LANGUAGE.
My problem is that, the following script I made works only with the first foreach run.
$abbr = $link->query("SELECT abbr AS langs FROM LANGS");
while($langs_db = mysqli_fetch_array($abbr)){
$site_langs[] = $langs_db['langs'];
}
$client_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
foreach($site_langs as $lang){
switch($client_lang){
case $client_lang == $lang:
header("location: http://www.mysite.com/$lang/index.php");
break;
default:
header("location: http://www.mysite.com/$lang/index.php");
break;
}
}
I thought a solution like:
case $client_lang == $lang:
$find "location: http://www.mysite.com/$lang/index.php";
break;
default:
$not_find = "location: http://www.mysite.com/$lang/index.php";
break;
And then:
if($find != ''){
header($find);
}else{
header(not_find);
}
But I'm not sure this it's a good idea...
Thank you!
// Set the default language as a fall back
$default_lang='en';
// Have an array with all languages your site supports
$langs=array('en', 'es', 'pt', /* etc... */);
// Query the browser's first preferred language
$client_lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// See if the language is supported otherwise redirect use the default one
$client_lang = (in_array($client_lang, $langs) ? $client_lang : $default_lang);
header("Location: /$client_lang/index.php");
Alternatively though you may want to consider gettext:
http://php.net/manual/en/book.gettext.php

Link that sets a parameter in the URL doesn't work as expected when I try $_GET

I have this PHP code that sets a cookie when the ?setLang parameter is in the URL
if (isSet($_GET["setLang"])) {
setcookie("lang",$_GET["setLang"]);
}
if (!isSet($_COOKIE["lang"])) {
//negociate language and set locale
}else{
//set locale to cookie
}
//translate with gettex
When I go to website.com/?setLand=en it works exactly as expected.
The problem is when I link to the URL in this form from website.com:
en
When I click it, through the link (and not go directly) the gettext translation doesn't work, but otherwise, it works as expected.
My first though was that I had to force some kind of refresh, so I did:
en
But it doesn't work.
I inspected the code and the cookie is in fact set when you click the link so it confuses me even further.
The full code just in case is the following:
<?php
if (isSet($_GET["setLang"])) {
setcookie("lang",$_GET["setLang"]);
}
if (!isSet($_COOKIE["lang"])) {
$langs = array(
'en-US',// default
'fr',
'fr-FR',
'de',
'de-DE',
'de-AT',
'de-CH',
);
$locale = substr(http_negotiate_language($langs), 0, 2);
}else{
$locale = $_COOKIE["lang"];
}
//if (isSet($_GET["locale"])) $locale = $_GET["locale"];
if($locale == "en")
$locale = "en_US.utf8";
if($locale == "de")
$locale = "de_DE.utf8";
if($locale == "fr")
$locale = "fr_FR.utf8";
putenv("LC_ALL=$locale");
setlocale(LC_ALL, $locale);
// Specify location of translation tables
bindtextdomain("translation", "locale");
// Choose domain
textdomain("translation");
// Translation is looking for in ./locale/de_DE/LC_MESSAGES/myPHPApp.mo now
// Print a test message
//echo _("title");
?>
and the link:
...
en
...
setcookie() adds a header to the output and does not alter the $_COOKIE superglobal.
if (isSet($_GET['setLang'])) {
$locale = $_GET['setLang'];
setcookie('lang', $locale);
} elseif (isSet($_COOKIE['lang'])) {
$locale = $_COOKIE['lang'];
} else {
$langs = array('en-US', 'fr', 'fr-FR', 'de', 'de-DE', 'de-AT', 'de-CH');
$locale = substr(http_negotiate_language($langs), 0, 2);
}
will do what you want.
When you have a link you don't need to reload anything, 'cause the link will be default (if you don't say it to don't) lead to another page.
Are you sure are you pointing it to the correct file? Try some debug like sending the exact file you are proccessing it in the URL, like for example:
en
For debugging propuses, you could use the PHP print_r that will help you understand what are you getting in $_GET.
Just do this in the start of your PHP code:
<?php
print_r($_GET);
//the rest of your code
?>

Multilingual Site - Redirection

I am trying to implement a language based redirection. Our site has sub-domains for different languages ie es.domain.com // de.domain.com etc. What i am trying to do is include the following code on all pages
<?php
$lng = array( 'en'=>'www', 'de'=>'de'); // more languages
$defaultLang = 'en'; // Index of the default (and fallback) language
$cookieName = "_dmLang"; // Set up the cookie name
$lang = trim(substr($_GET['lang'], 0, 2));
if (empty($lang)) $lang = trim($_COOKIE[$cookieName]);
if (empty($lang)) $lang = trim(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
if (empty($lang) || empty($lng[$lang])) $lang = $defaultLang;
setcookie($cookieName, $lang, time()+3600*24*30);
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://".$lng[$lang].".domain.com" . $_SERVER['REQUEST_URI']);
?>
The language will change when you call /?lang=de
Are there any server/load implications when using this code? Is there a better way to implement this?

Categories