0
votes

Is there any way to change a parameter in a url request on load?

My route basically checks for a language in the url http://localhost/<language>/<controller>

However the problem is that if a random text is inserted in the language parameter, it then loads the default text which the way I set up the translation files will output things like menu.home

Is there anyway for a controller to redirect to a url with the default language? for example http://localhost/fakeLanguage/home will redirect to http://localhost/en/home and http://localhost/fakeLanguage/about redirects to http://localhost/en/about

2

2 Answers

1
votes

Your Route must filter segments with regex, something like this:

// load available language names from config
$langs = Kohana::$config->load('lang.available');
Route::set('lang_route', '<language>/<controller>', array('language' => '('.implode('|', $langs).')'))
    ->defaults(...);

Or use route filters, which can easily modify route segment values.

0
votes

While this is only a rough idea of one possible solution, you may want to consider defining an array of all the supported languages. Something like this:

<?php
/*
    Part 1 - Create an array of all the known languages. Consider making this part of the application configuration file.
*/
$languages = array(
    "en",
    "ge",
    "pirate"
);
?>

And then check against that array within the controller file. Perhaps using the controller's before method:

<?php
/*
    Part 2 - In the controller file add a before method that checks to see if the requested language exists.
*/
public function before(){
    if(!in_array($this->request->param('langauge'),$languages)):
        // If the language is unknown perform a redirect.
        url::redirect('DEFAULT_LANGUAGE_URL');
    endif;
}
?>

Converting the first segment of the URL structure above can be done with code like:

<?php
    // Get the current URI
    $url = $this->request->detect_uri();

    // Get the query string
    // Note: If you aren't interested in preserving the query string this next line can be removed.
    if($_SERVER['QUERY_STRING'] != '') $url .= '?'.$_SERVER['QUERY_STRING'];

    // Set the default language. Consider setting this in your application configuration file instead.
    $defaultLanguage = 'pirate';

    // Replace the first URI segment with the default language.
    $redirectURL = preg_replace("/^\/.*?(\/.*)$/",("/{$defaultLanguage}$1"),$url,1);
?>