Language neutral entry pages - php

My old web site has an index.html page … nothing strange! Everything is fine.
The new web site has an english and a french version, so the new index is index.php?lang=eng…. That makes sense.
I don’t like to make a front page that will say “english” or “french”. But that’s not good for ranking or seo.
So the question is: How do I manage to get a default index.php with request (?lang=eng) to become the front page?

domain.com/en/index.php
domain.com/fr/index.php
Use url rewriting with regular expressions (mod_rewrite, ISAPI, whatever) to handle requests to relevant pages so
domain.com/en/index.php REWRITE TO domain.com/index.php?lang=en
domain.com/fr/index.php REWRITE TO domain.com/index.php?lang=fr
This way your pages are two seperate pages to search engines but handled via one gateway in code. I'm not a regex expert but it would be a very simple regex I would imagine

I'm not sure I understand the question. It seems to have two parts:
How to provide a default language of English:
$lang = empty($_GET['lang']) ? "eng" : $_GET['lang'];
Do you also have a problem of where to put the English/Francais links so search engines don't ding you? I wasn't aware of this problem.
It might also help to let us know if you're using a CMS, and if so which one.

Unless I'm misunderstanding the question, in index.php, when you check the language, put something like this:
$lang = #$_GET['lang'];
if ( empty($lang) ) $lang = 'eng';

Just put an argument in the php code that says :
if (lang == "") // haven't done php in a while so the syntax is probably wrong
{
lang = "eng";
}
In other words, if there isn't an argument on the lang variable, you can just set it to be eng automatically, and so the first page will default to English every time, unless told otherwise.

Just make the default english and offer an option on the index page to change to french? This, of course, depends on what language most of the visitors speak, which isn't all that hard to figure out with visitor logs.

I would use a neutral URL for entry, such as:
http://example.com/foo/bar
On this page I would do some language negotiation or simply ask the user for the prefered language. Then I can redirect to the language specific URL:
http://example.com/en/foo/bar

what do you think about that solution
<?php
$lang = $_GET['lang'];
if ( empty($lang) ) $lang = 'fra';
header( 'Location: http://acecrodeo.com/new/01-acec.php?lang='.$lang) ;
?>

Related

PHP: A way to manually switch languages?

I have a website that has the following language switching algorithm:
First, it detects the default browser language (I do not know why? but Chrome always gives something like en-EN,ru,lv, so Chrome's default language always is English, it seems).
Then it writes the language value into a session variable lang and requests the desired string file (i.e. /assets/includes/en-US/strings.php);
And every string from this file is being included in the HTML code, so the pure HTML has not any plain text in.
Of course, a default language detection is not the reason to stop - I need a manual language switcher like links (LV | EN | RU). So, what id the possible (and maybe the best) way to switch the language and to overwrite the session variable after user clicks to the desired language?
The best way is the simpliest way :)
$langs = array('LV', 'EN', 'RU');
<?php foreach ($langs as $lang): ?>
<?=$lang;?>
<?php endforeach; ?>
so you give the user opportunity to change lang via GET in this example.
Overwrite the session to the sent request:
<?php
if(in_array($_GET['lang'], $langs) {
$_SESSION['lang'] = $_GET['lang']; // to prevent user to change its session to something you don't want to
}
?>
Afterwards you just interact with this session to display content.
You can use redirection, if you have each page written in different language:
(but I guess the logic how to interact with the language you have already implemented from the automatic language detection, but still... let me suggest some ways at fast?)
<?php
if (isset($_SESSION['lang']) && $_SESSION['lang'] !== 'EN') {
header("Location: mysite.com/".$_SESSION['lang']."/index.php");
exit;
}
?>
Or, you can use translation method.
All of your translations are in a database under columns with the same names as your $langs array.
So you output the content from this particular column:
SELECT lang_{$_SESSION['lang']} FROM translations WHERE string = '$string';

Auto detect language and redirect user

I am doing my own website and I managed to write some code that makes directs user to the language version according to the browser's language. Here is the script:
<?php
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "sv")
header("location: index.php");
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"] == "pt")
header("location: pt/index.php");
else
header("location: en/index.html");
?>
I have put this in the index.php before the . It seems to be working because I am not in an English speaking country but my browser is in English and I am being redirected to the English version.
Is this correct? Is there a better/cleaner way to do this?
PHP 5.3.0+ comes with locale_accept_from_http() which gets the preferred language from the Accept-Language header.
You should always prefer this method to a self-written method as the header field is more complicated than one might think. (It's a list of weighted preferences.)
You should retrieve the language like this:
$lang = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
But even then, you won't just have en for every English user and es for Spanish ones. It can become much more difficult than that, and things like es-ES and es-US are standard.
This means you should iterate over a list of regular expressions that you try and determine the page language that way. See PHP-I18N for an example.
Well, I came across some problems with my code which is no surprise due to I am not a PHP expert. I kept therefore on searching for a possible solution and I found the following code on another website:
<?php
// Initialize the language code variable
$lc = "";
// Check to see that the global language server variable isset()
// If it is set, we cut the first two characters from that string
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
$lc = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
// Now we simply evaluate that variable to detect specific languages
if($lc == "fr"){
header("location: index_french.php");
exit();
} else if($lc == "de"){
header("location: index_german.php");
exit();
}
else{ // don't forget the default case if $lc is empty
header("location: index_english.php");
exit();
}
?>
This did the job perfectly! I only had a problem left. There was no way to change language, even with direct links into another language because as soon as the page was loading, the php block would redirect me to the borwser's language. This can be a problem if you are living in another country and have for instance Swedish as a mother language but you have your browser in English because you bought your computer in the UK.
So my solution for this issue was to create folders with a duplicate version for every language (even the one for the main language) without this php code on the index.html (and therefore not index.php). So now my website is auto detecting the language and the user also has the option to change it manually in case of they want!
Hope it will help out someone else with the same problem!
I think your idea is great. May be help you shortest code:
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
header("location: ".$lang."/index.php");
That should work fine. You could also use http_negotiate_language and discusses here
Most useful this code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if(file_exists('system/lang/'.$lang.'.php'))
{
include('system/lang/'.$lang.'.php');
}else{
include('system/lang/en.php'); //set default lang here if not exists translated language in ur system
}

Best way to achieve multilingual URLs?

I'm developing a niche social networking site that is going multilingual. That means our current URL structure will soon need to start using translated words for slugs like the following:
www.example.com/home becomes www.example.com/inicio
www.example.com/profile becomes www.example.com/perfil
www.example.com/help becomes www.example.com/ayuda
And so on. My question is: what's the best way to support this in a PHP application? For incoming requests, I thought a dictionary like the following in my router.php file would suffice:
<?php
$request = explode("/", trim($_SERVER['REQUEST_URI'], "/"));
// Dictionaries of page slugs.
$slugs = array(
'es' => array(
'inicio' => 'home',
'perfil' => 'profile',
'ayuda' => 'help',
)
// additional languages can be added here
);
// Rewrite any incoming (foreign) requests
if ($host=="www.example.es") { // to be made programmatic
$lang = "es"; // pick up from locale constant rather being hard-coded
if (array_key_exists($request[0], $slugs[$lang])) {
$request[0] = $slugs[$lang][$request[0]];
}
}
...
Which basically takes URL segments and matches them against an English counter-part if it exists. If not, then it will proceed as normal and most likely cause a 404 as a controller doesn't exist for URL segment.
Although this words, I need it to be backwards-compatible too. For example, when building URLs in my application.
Naturally, as the application is only English at the moment these are just hard-coded. So say, when fetching a User object I do the following:
<?php
class User {
function __construct($id) {
// fetch user details
$this->profile_url = ROOT . "/profile/" . $this->username;
}
}
What is the best method to then replace instances of "/profile/" being hard-coded to getting the translated version, i.e. "/perfil/" in the Spanish site?
I could always be wrong, but here goes...
The standard way to achieve multilingual websites is to use i18n dictionary/template techniques in which you have a separate dictionary for each language, and in some cases different templates.
However, in such cases, I have never seen anybody change the language of their URL's. URL's map a request to files on the server disk (generally speaking), and there for shouldn't change based on language if you can avoid it.
It is common to prefix the 'path' section of your URL with the language you are requesting - ie:
http://foo.bar/en-us/foobar.html
To summarize:
I wouldn't worry about translating your URLs as it isn't a standard practice (atleast, not that I have seen). Simply prefix the URL 'path' with a language denotation such as in the URL above.
I have something similar in an application I'm developing.
Each page has a unique ID which is matched to a slug, page title, meta description and such for each language in a table.
As for the people saying it's not standard practice and not to bother with it I disagree as having nicely translated URLs can help your SEO in different languages.
Well, a common pattern I've seen for php is to create a php file for each language and initialize a large dictionary in which the keys are the same for all languages.
Have a session variable called language which can initially be 'en' for english (or whatever you prefer), and then include using command "include(language . '/main.php');" in which you have a folder called 'en' which contains all php files to include for translations. If main gets too large, you can subdivide and include whichever translation serves your needs (for example a /en/forum.php for forum translations and a /en/blob.php for front page translations).
It has the tremendous advantage of being flexible and allowing you to control the language simply by modifying one session variable. You can even do tricks like detect browser language settings and assign language according to that if it hasn't already been defined rather than simply making it english.
I was thinking about this, as I'm going down this path now. I was going to use a similar method, but not the same...
I was going to have language "include" files with all the strings of the site. So...
/languages/en.php
would have all the correct strings for the English language, and the other language files could be dropped in as new translations are done.
In the en.php file, I was going to put in fields like this
define('PageTitleWelcomeMessage', 'Welcome to Foo');
And then call that static variable anywhere in the site. The en language would be defined in their profile
I could then call that variable like so:
echo PageTitleWelcomeMessage;

How do you create domain.com/?stringhere without a .php extension

I want to create a link like the following:
http://www.myurl.com/?IDHERE
What i want to be able to do is be able to goto the above link, and then pull whats after the ? (in this case IDHERE) and be able to use that information to perform a MySQL lookup and return a page.
Can anyone point me into the right direction? please know this is using PHP not ASP
The issue here is not with your scripting language, but with your web server setup. I'll refer to these by their Apache names, but the features should be available in most web servers.
There are three features you might want to use:
1) content negotiation (mod_negotiation), which allows your web server to try a specified list of extensions in a specified order, for example: http://example.com/foo might be http://www.example.com/foo.html or http://example.com/foo.php
2) DirectoryIndex, which tells the web server that when a client asks for http://example.com it should look for a specified list of files in order, so it might server up http://example.com/index.html or http:/example.com/index.php
3) mod_rewrite, which allows you to basically rewrite the URL format received by the server. This allows you to do things like translate http://example.com/foo/bar/baz to http://example.com/foo/bar.php?page=baz
The rest is done by the backend script code as normal.
Create a default PHP file in that directory that will get loaded when no file name is specified (e.g. index.php). In your PHP script you can get the part after the question mark from the variable $_SERVER['QUERY_STRING'].
Do the following in your site's main index.php:
list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.
In the link, form or whatever - index.php?id=someid
In your index.php file:
$_GET['id'] = $id
Now you can use it:
e.g.
echo $id;
Since it's your default page, it will work without the extension.
list($id) = array_keys($_GET);
// right now, $id represents the ID you're looking for.
// Do whatever you want with it.
this was exactly what i was looking for, though now i just need to create something to notify if nothing is there or not. Thank you all for your responses.
I would solve it by using .htaccess file if possible.
create a .htaccess file in the main directory with the content:
RewriteEngine on
RewriteRule cat/(.*)/(.*)/(.*)/$ /$1/$2.php?$3
that should translate "example.com/foo/bar/baz" to "example.com/foo/bar.php?page=baz"

multilingual php script question

I have this PHP script. It's the only one that really worked to me:
<?php
/*Check_if_user_has_changed_language: */
if(isset($lang)){/*If_so:*/
setcookie("ling",$lang,time()-60*60*24*365,"/",".sayip.info",0);/*Wipe_previous_cookie*/
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);/*Whatever_the_means_lang_has_been_stored,_store_latest_lang_in_new_cookie:*/
//echo "<script language=\"JavaScript\">alert('Selected language=$lang')</script>";/*UnComment_to_check*/
}else{/*If_user_has_NOT_changed_language:*/
if(isset($_COOKIE['ling'])){/*Check_if_user-language_cookie_is_set._If_so:*/
$lang=$_COOKIE['ling'];
setcookie("ling",$lang,time()-60*60*24*365,"/",".sayip.info",0);/*Wipe_previous_cookie*/
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);
//echo "<script language=\"JavaScript\">alert('Cookie language=$lang')</script>";/*UnComment_to_check*/
}else{/*If_user-language_neither_selected_nor_in_cookie,_choose_browser_language:*/
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2);
setcookie("ling",$lang,time()+60*60*24*365,"/",".sayip.info",0);
//echo "<script language=\"JavaScript\">alert('Your browser language=$lang')</script>";/*UnComment_to_check*/
}
}
?>
First the code detects the language of the user's browser. That's ok.
Then stores the info in a cookie. That's ok.
Well in this piece of code its everything ok. What I really need is to create an option for visitors change the language. I was thinking something like linked flag images so when someone click on the flag it changes the language.
Can someone explain to me through an example or even a clean, full solution? My skills in PHP are poor.
Thanks in advance.
I would put the selected language in the URL, e.g http://example.com/en/foo/bar. This makes the selected language transparent and easy to change.
i would put to if i knew how to lol...Since i got this script working after testing more or less 10 different scripts, im not like falling back, just need an example in how to put flags and when someone click on the flag it changes de value of the cookie...
I'm not sure if I got your question right
if your gonna place a link for each language in your page, make the link something like
http://www.example.com/?lang=jp
then in the php code before the script that you posted add
if (isset($_GET['lang'])) $lang = $_GET['lang'];
is this what you ment?
A more elegant solution may be to check the user's headers. Most browsers will allow users to set their preferred language in preferences. This in turn sends an HTTP header with the request. The header looks like this.
Accept-Language : en-us,en;q=0.8,ar-ly;q=0.5,id;q=0.3
The value is a comma-delimited list of accepted languages, ordered by preference ( the q=x part is the preference). This way, you can automatically detect what language the user has opted to see the web, and display it if you have it.

Categories