best way to change current site language - php

i am creating a website by two language with php. to change language of pages , i create to link like this:
FA|EN
this two link is on a page named header.php that includes on some page.but in some pages is some parameters that send via URL . So that two link are not true and they Should be as follows:
FA|EN
my Question is how i create a dynamic links for all page Even if have some parameters.

You need to store the value in a global key, preferable php's $_SESSION
in the beginnen of your page you can then check with the following :
session_start(); // if not started already
$possible_languages = array('en', 'fr');
$default_language = 'fr';
$_SESSION['lang'] = ( isset($_GET['lang']) && in_array($_GET['lang']) ? $_GET['lang'] : $default_language );
From now on you can $_SESSION['lang'] where needed

You could use:
<?
$params = $_GET;
$params['lang'] = 'EN';
$qs = '?';
foreach($params as $k=>$v)
$qs .= $k.'='.urlencode($v).'&';
$url = substr($_SERVER['PHP_SELF'].$qs, 0, -1);
echo $url; //EN
$params['lang'] = 'FR';
$qs = '?';
foreach($params as $k=>$v)
$qs .= $k.'='.urlencode($v).'&';
$url = substr($_SERVER['PHP_SELF'].$qs, 0, -1);
echo $url; //FR
?>

First, store the language in session or cookie.
Second, build link creation mechanism for your website using the current language setting, do not echo the internal links directly. Important internal links should be created from functions so that they format can be change quickly later.

Related

How to automatically reflect changes when adding PHP cookie?

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

A better way to use mod_rewrite & php in translating pages?

I am trying to translate these pages from English to French:
/about.php
/contact.php
/paintings.php?id={$id}&title={$title}
I created the following link:
<?php if($language !== 1): ?>English<?php else: ?>French<?php endif; ?>
With this code behind it:
$url = $_SERVER["REQUEST_URI"];
if (isset($_GET['lang'])) {
$pattern1 = '&lang=' . $_GET['lang'];
$pattern2 = '?lang=' . $_GET['lang'];
$patternTotal = array($pattern1, $pattern2);
$url = str_replace($patternTotal, '', $url);
$language = 1;
}
else if (strpos($_SERVER["REQUEST_URI"], '?')) {
$url .= '&lang=en';
$language = 0;
}
else {
$url .= '?lang=en';
$language = 0;
}
What I want for it to do is to return 1 to $language if the lang parameter is set to any value. Then I will use an if statement to fetch and display the content accordingly.
However I realized that this url /paintings.php?id={$id}&title={$title} looks bad and I used mod_rewrite to get it to this version /{$id}/{$title} with this RewriteRule ^([^/]*)/([^/]*)$ /photo.php?id=$1&title=$2 [L]. And things broke. While the $url works on all the other pages on the paintings one it doesn't.
I have a feeling that I got it all wrong. How can I make it work? Also, is there a more efficient way in doing this?

Yourls - Some custom URL are shorten some not

Some of my Pages gives a correct shorten URL back but some of the will not. Even they are shorten at Yourls. I can see it at the Admin Panel.
This is the debug of a Page with shorten URL
{"status":"fail","code":"error:url","url":{"keyword":"09266","url":"http:\/\/domain.com\/LilyPad-Arduino-328-Main-Board","title":"LilyPad Arduino 328 Main Board","date":"2015-02-12 00:35:39","ip":"xxx.xxx.xxx","clicks":"0"},"message":"http:\/\/domain.com\/LilyPad-Arduino-328-Main-Board already exists in database","title":"LilyPad Arduino 328 Main Board","shorturl":"http:\/\/doma.in\/09266","statusCode":200,"qrcimg":"http:\/\/doma.in\/user\/plugins\/inline-qrcode\/images\/qrccf6f0d99893974288d48676d9cdbd51a.png","qrimage":"
This is the debug of another Page without the URL on Page but available at Admin
{"status":"fail","code":"error:keyword","message":"Short URL 00027 already exists in database or is reserved","statusCode":200,"qrcimg":"http:\/\/doma.in\/user\/plugins\/inline-qrcode\/images\/qrcd41d8cd98f00b204e9800998ecf8427e.png","qrimage":"
This is my PHP Code
function shortyourls(){
global $smarty;
// Inputs
$shorturl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$signature = "123456789";
$siteurl = "http://doma.in";
$format = "json";
$Artikel = $smarty->get_template_vars('Artikel');
$title = http_build_query(array('title' => $Artikel->cName));
$keyword = preg_replace("/[^0-9,.]/", "", ($Artikel->cArtNr));
// Phases url
$short = file_get_contents($siteurl.'/yourls-api.php?signature='.$signature.'&action=shorturl&url='.$shorturl.'&format='.$format.'&keyword='.$keyword.'&'.$title);
$url=json_decode($short,TRUE);
$output = $url['shorturl'];
echo $output;
}
Any idea what is wrong?

Adding a extra path after domain

If trying to add a extra path in URL after my domain in all urls
$extra = "en";
$domain = "http://domain.com";
$current = currentURL();
$rest_path = str_replace($domain,'',$current);
$result = $domain."/".$extra.$rest_path;
// $result is "http://domain.com/en/mysub/mysub"
After this so I redirect my site via using PHP redirect
To get current url is doing like..
function currentURL() {
$pageURL=(#$_SERVER["HTTPS"]=="on")?"https://":"http://";
if($_SERVER["SERVER_PORT"]!="80"){
$pageURL.=$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}else{
$pageURL.=$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}
It's look like many steps , Any easier to do that ? Or review my bad coding pls.
PS : Try to do without using .htaccess
I would use just:
$extra = "en";
$domain = "http://domain.com";
$result = $domain."/".$extra.$_SERVER['REQUEST_URI'];
since you are not using protocol or domain name.
$extra = 'en';
$domain = $_SERVER['SERVER_NAME'].'/'.$_SERVER['REQUEST_URI'];
$new_url=str_replace('.com','.com/'.$extra,$domain);
No?

PHP Code Cleaning

Am running the following code to gather some data from my page and store it in my database, however, i need to add some extra functionality to it but i don't seem to be able to do it correctly.
The Code:
// Get Referrer and Page
if (isset($_GET["ref"]))
{
// from javascript
$referer = $_GET["ref"];
$page = ((isset($_SERVER['HTTP_REFERER'])) ? (parse_url($_SERVER['HTTP_REFERER'], PHP_URL_PATH)) : (''));
}
else
{
// from php
$referer = ((isset($_SERVER['HTTP_REFERER'])) ? ($_SERVER['HTTP_REFERER']) : (''));
$page = $_SERVER['PHP_SELF']; // with include via php
}
// Cleanup
if (basename($page) == basename(__FILE__)) $page = "" ;
This script is storing $page as "/site/index.php or /site/about.php", for example. I kinda want it to store it as "Index or About" without the whole /site/ and .php part.
Thanks in advance
Use pathinfo(), for example:
<?php
$page = "/site/index.php";
$page_info = pathinfo($page);
$page_name = $page_info['filename'];
echo $page_name; //output: index
?>

Categories