user1658741
user1658741

Reputation: 1

.htaccess tricks for multi-language website

Right now, I have a website that uses two languages (French and English).

The way it currently works is that if someone goes to mysite.com/folder/file.php for example, file.php is simply a script that figures out which language to use, gets it's own path and filename (file.php) and serves up mysite.com/en/folder/file.php (if the language is English). However, what shows up in the URL is still mysite.com/folder/file.php.

For any folder and any file, the same script is used. If I want to add a new file, I have to add the file to the folder the user types into the browser as well to the en and fr folders.

Could I do some .htaccess tricks so that whatever URL is typed, one .php file gets opened, checks the language and the folder/file which is requested, and then serves up the correct language file?

Here's the php file that is served up for any files in the URL.

<?php 

// Get current document path which is mirrored in the language folders
$docpath = $_SERVER['PHP_SELF'];

// Get current document name (Used when switching languages so that the same
current page is shown when language is changed)
$docname = GetDocName();

//call up lang.php which handles display of appropriate language webpage.
//lang.php uses $docpath and $docname to give out the proper $langfile.
//$docpath/$docname is mirrored in the /lang/en and /lang/fr folders
$langfile = GetDocRoot()."/lang/lang.php";
include("$langfile"); //Call up the proper language file to display

function GetDocRoot()
{
 $temp = getenv("SCRIPT_NAME");
 $localpath=realpath(basename(getenv("SCRIPT_NAME")));
 $localpath=str_replace("\\","/",$localpath);
 $docroot=substr($localpath,0, strpos($localpath,$temp));
 return $docroot;
}

function GetDocName()
{
$currentFile = $_SERVER["SCRIPT_NAME"];
$parts = Explode('/', $currentFile);
$dn = $parts[count($parts) - 1];
return $dn;
}

?>

Upvotes: 0

Views: 1026

Answers (1)

Matt S
Matt S

Reputation: 15374

A common solution is to have the root of the site (/index.php) figure out the preferred language and then redirect to a URL containing the language code. If your files are then separated by language on disk they can be requested directly.

Or you can add a simple regex in .htaccess or your host setup to grab the language out of the requested URL and send all similar requests to one file:

RewriteEngine On
RewriteRule ^/(.+)/folder/file.php$ /folder/file.php?lang=$1

Then reference $_GET['lang'] in PHP to see which language was requested. You'll probably want to expand this to be more generalized for all similar files on the site, e.g.:

RewriteRule ^/(.+?)/(.+)\.php$ /$2.php?lang=$1

Upvotes: 1

Related Questions