Words from Alejandro U. Alvarez
Simple CMS with language changer functions (v. 1.1)
Introduction:
Today I'll show you a way of translating your website very easily, and then have the browser detect user language automatically.
First you need some sort of php template system, I'll show you the one that I've developed, which is not very advanced but works perfectly for small sites.
What it does is in each page there is always a part that repeats. In my main page the repeating part is the header, left sidebars, and footer. And the only thing that changes is the content. What I did is a class called page, and that class generated the code needed for the header, sidebar and footer. The content is included from a folder called "content", which then contains subfolders, each named with the language code, so if the folder contains the spanish translation it would be named "es". (See all language codes)
Another class is "session", it does a check for new users or returning users based on session variables that store their preferred language, it also checks for the URI changer (?lang=...), and if none of that is found, it then checks for the user OS language, then checks if it is available and if it is, it sets it as preferred language of the site, if not, the default language is selected.
Codes for this:
The following codes must go in a folder structure like so "lib/content/". This can be change, but it makes it more easy to understand.
At the bottom of this there is a link to a zip file containing all necessary files to have this work
The filenames I used are: "page.php" for the page object, and "session.php" for the session object.
The page object (simplified):
//This contains the page object - Used to generate the page layout class Page { var $timep = 0; //functions to display a page: function genTop($title,$extraCSS='',$extraScripts='',$extras=''){ //for the top part (doctype...) //setup time counter $this->timep = round(microtime(), 3); //start file inclusion include('lib/content/core/doctype.htm'); //includes opening html tag and head include('lib/content/core/metas.htm'); //includes the meta data (All the same) $metaLang = $_SESSION['lang'].'-'.strtoupper($_SESSION['lang']); echo '<meta http-equiv="Content-Language" content="'.$metaLang.'" />'; //language meta tag if($title !== ''){ $title = $title.' | '; } //add | if necesary echo '<title>'.$title; switch($_SESSION['lang']){ case 'es': echo 'Fundacion Urbano Alvarez'; break; case 'en': echo 'Urbano Alvarez Foundation'; break; } echo '</title>'; include('lib/content/core/link-rel.htm'); //includes the linking css if($extraCSS !== ''){ //Get an array with all extra style sheets $css = explode(',',$extraCSS); $totalCSS = count($css); //now iterate through all extra css for($i=0; $i<$totalCSS; $i++){ echo '<link rel="stylesheet" type="text/css" href="'.$css[$i].'" media="all" />'; } // } include('lib/content/core/scripts.php'); //includes all javascript scripts if($extraScripts !== ''){ //get an array with all extra scripts $scripts = explode(',',$extraScripts); $totalScripts = count($scripts); //Now include all extra scripts for($i=0; $i<$totalScripts; $i++){ echo '<script language="javascript" type="text/javascript" src="'.$scripts[$i].'"></script>'; } // } echo $extras; // Any extra code that may be entered before the head echo '</head>'; // echo '<body>'; include('lib/content/core/top.php'); include('lib/content/core/left.php'); //The left navigation column echo '<div id="content">'; } function genContent($pageName=''){ global $session; if($pageName == ''){ $pageName = $session->url; } include('lib/content/'.$_SESSION['lang'].'/'.$pageName); } function genBottom($extraFooter='',$extraScripts=''){ if($_SESSION['lang'] == 'es'){ $changeLang = 'Cambiar idioma a: <a href="?lang=en">English</a>'; }else{ $changeLang = '...'; //Here goes code for extra stuff (I use it for stumbleupon) } echo '<p>'.$changeLang.'</p>'; echo '</div><!-- end .content -->'; echo '<div id="footer">'; echo '<div id="footerLeft"><img src="img/body/footerLeft.jpg" width="41" height="93" /></div>'; echo '<div id="footerText">'; $time2 = round(microtime(), 3); $gen = $time2 - $this->timep; if($_SESSION['lang'] == 'es'){ echo 'Spanish footer'; }else if($_SESSION['lang'] == 'en'){ echo 'English footer'; } if($extraFooter !== ''){ echo $extraFooter; } echo '</p>'; if($_SESSION['lang'] == 'es'){ echo 'Spanish bottom links'; }else if($_SESSION['lang'] == 'en'){ echo 'English bottom links'; } echo '</div>'; echo '</div><!-- end .footer -->'; include('lib/content/core/analytics.htm'); //google analytics code if($extraScripts!==''){ echo $extraScripts; } echo '</body></html>'; } }; ?>
So now the session class:
//proc all page display include('lib/content/lang.php'); //language detector include('lib/content/page.php'); $page = new Page; class Session { var $lang; //Username given on sign-up var $url; //The page url current being viewed var $referrer; //Last recorded site page viewed /* Class constructor */ function Session(){ $this->time = time(); $this->startSession(); } function cf($filename){//function to clean a filename string so it is a valid filename $fp = explode('/',$filename); $num = count($fp); return $fp[$num-1]; } /** * startSession - Performs all the actions necessary to * initialize this session object. Tries to determine if the * the user has logged in already, and sets the variables * accordingly. Also takes advantage of this page load to * update the active visitors tables. */ function startSession(){ session_start(); //Tell PHP to start the session /* Set referrer page */ if(isset($_SESSION['url'])){ $this->referrer = $search = $this->cf($_SESSION['url']); }else{ $this->referrer = "/"; } /* Set current url */ $this->url = $_SESSION['url'] = $this->cf($_SERVER['PHP_SELF']); /* Set user-determined language: */ //set up languages array: $langs = array('en','es'); // if(isset($_GET['lang'])){ if(in_array($_GET['lang'],$langs)){ $this->lang = $_SESSION['lang'] = $_GET['lang']; } } if(!isset($_SESSION['lang']) || !in_array($_SESSION['lang'],$langs)){ $this->lang = $_SESSION['lang'] = language(); } } }; /** * Initialize session object */ $session = new Session; ?>
Well so those are the classes used to format page display. I think they are pretty self-explanatory but if you have any doubt about their usage, comment it.
Using it:
So once you have all set up create a new php file in the root "/". I'll name it "test.php". This file is the generator of the test page. What you need now is a folder inside "lib/content/" with the language code of the language used. I have two, one with "es" and another one with "en", for spanish and english respectively.
To change languages, put a link with this: <a href="?lang=((New lang code here))">Change language to...</a>
Now paste the following code in there:
$title['es'] = 'Bienvenido a la pagina de prueba'; $title['en'] = 'Welcome to the test page'; $page->genTop($title[$_SESSION['lang']]); $page->genContent(); $page->genBottom(); ?>
What this does is it first includes the session.php, with the object initializers. Then it creates an array with the different titles, one for each language offered. Then it calls the object "page" to create the page, in three steps. Top, content, and footer.
The content is retrieved from the appropriate folder ("en" for english, "es" for spanish, and so on ...), by including a file called exactly the same as the generator file, so in this case ("test.php"), supposing you are browsing the english version, it will include the file "lib/content/en/test.php" which should contain plain html like the following:
<h2>This is a test page</h2> This is some content...
And this is it!
Download example (zip):
Here you can download a zip with all files for example purposes:
Pack with all necessary files (Zip package)
File structure of the zip:
- lib
- content
- page.php
- session.php
- lang.php
- otherLangs.php
- core
- doctype.htm
- metatags.htm
- Other .htm files needed
- en
- test.php
- es
- test.php
- content
- test.php
The otherLangs.php contains an array with all possible language codes, so if you don't know a language code you can check it there.
The lang.php file contains a function used to check the user preferred language, you can probably understand how it works by looking at it.
| Print article | This entry was posted by alex on March 17, 2008 at 11:53 am, and is filed under PHP, Programming, Web-related. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
No comments yet.
No trackbacks yet.
Display timezone-specific dates in PHP
about 3 months ago - No comments
It’s common to have a website designed for one country (For example Spain or the UK) and have it in a server elsewhere (In the US for example). You will notice that sometimes when displaying a date this way, it shows the local time at the server!
Instead of manually correcting this time difference there is More >
New threat for all Joomla and WordPress installations
about 10 months ago - 3 comments
There is a new BOT out there, and one of the bad ones. I have started receiving traffic from it in my servers over the past week, and after some investigation it turns out it is quite a powerful bot, and so simple to use even a kid with a computer could use it.
The bot More >
Parse links in user comments
about 10 months ago - No comments
When you allow users to comment and post stuff to your website, it is interesting and useful allowing them to post links and other stuff. But how can we do so easily?
Surely there is BBCode, phpBB, allowing only some HTML tags… etc but how easy is this approach for the end user? Of course some More >
Calculate age in PHP from timestamp
about 10 months ago - No comments
If you ever wanted to calculate someone’s age in PHP from a birth timestamp, you must take into account that the age is more than the number of years, since days and months are also important, so I wrote a simple function that will return the exact age for a given timestamp:
function getAge($birth){
$t = time();
$age More >
Easiest PHP file upload
about 11 months ago - No comments
Hello people,
I want to share with all of you a file upload class I have developed, that makes it stupid simple to upload files haha
The PHP class:
First of all, here is the PHP class you will need:
< ?php
//Uploader class, by Alex
// This class is meant to handle all kinds of file uploads for DJs Music
// More >
Easily assign an image to a post in WordPress
about 1 year ago - 1 comment
Have you ever wondered how to assign an image to a certain post using WordPress? Surely there are some plugins that try to do this, and maybe they accomplish it, but probably slowing down your blog.
Well, here is a way of doing it without slowing the blog or installing any sort of additional plugins. When More >
Country lists in most popular languages
about 2 years ago - 14 comments
If you are developing a website and you need a <select> list of countries, here is your ultimate resource: Full country lists in all the most popular languages, in alphabetical order.
They are in the form:
<option value=”2 letter country code”>Country name</option>
Chose from the following list for ease of navigation:
English list
Spanish list [Español]
Italian list [Italiano]
German list [Deutsche]
French More >
Did you mean… ? In php
about 2 years ago - 13 comments
In a new website I am developing for a client I had to add the usual “Did you mean… ?” in the search results for her. Si I started thinking for the easiest way to do this.
There are actually a lot of php functions out there to look for similar text. The most obvious one?
similar_text()
You More >
How we became web developers…
about 2 years ago - 3 comments
I normally write to those web developers/programmers who are already good, experienced, and thus the articles are somewhat advanced.
But today I got up feeling nostalgic I guess, or I just felt like remembering back on my www birth, on my first impression of the Internet, my first site online, my first steps in w3c standards, More >
Using Gravatars in your blog comments
about 2 years ago - No comments
I’m sure you have seen in some blogs or websites that as soon as you enter your email, or other people do, an avatar is displayed for them. If you haven’t still set your own you should do that now.
A Gravatar is a “Globally Recognized Avatar”, meaning that anyone can display yours if they know More >