langauage web. I set 3 links, Français... (href=changeLanguage.php?lang=fr,es,en)
changLanguage.php
session_start();
if(isset($_SESSION['bckTo']) && isset($_GET['lang'])){
$lang = preg_replace('/[^a-z]/','',trim($_GET['lang']));
#TODO
#More vlidation ...
$full_url = $_SESSION['bckTo'];
$full_url = str_replace(array('&lang=en','&lang=es','&lang=fr'),'',$full_url);
header('Location: '.$full_url.'&lang='.$lang.'');
}
$_SESSION['bckTo'] save the current URL for example: mysite.com/index.php?id=x&n_d=y
The problem is, the header translate the URL to: mysite.com/index.php?id=x&n_d=y&lang=en.
Any idea will be appreciate
Why not just set the language in session instead of via GET? Then you just have to put a link to change the language and and then redirect to the page. This would probably be best, given that you are already using sessions.
Example:
English
On the changeLanguage:
//code up here
if (isset($_SESSION['bckTo') && isset($_GET['lang'])) {
// $lang code here
$_SESSION['lang'] = $lang;
header('Location: ' . $_SESSION['bckTo']);
}
Then you would just need to change your language checking / displaying code to check the session variable rather than the GET (on the actual pages).
Running html_entity_decode will convert those HTML entities back into ampersands.
http://us2.php.net/manual/en/function.html-entity-decode.php
Related
So I'm building a small multilingual (French + English) website and there is a little bug. I would like to remove the "english default" language in the code, so if a user picks french on one page, any page he will select afterwards will be in french and not be "back" to english. Same if the user picks english in the first place. But since there will be more french users, I would like it to be the default language on the home page.
The content is in folder with prefixes: fr_language.php and en_language.php
The lang.php file here
Links for FR or EN
Français
English
And the navigation
<ul>
<li><?php echo $lang['home']; ?></li>
<li><?php echo $lang['services']; ?></li>
<li><?php echo $lang['aboutus']; ?></li>
<li><?php echo $lang['contact']; ?></li>
</ul>
Thanks for your help!
EDIT:
Ok great, with your help it's working! In my "nav.php" include, I wrote this. Perhaps it's possible to do a cleaner version, haha! Any ideas? Thanks again!
Consider using the following approach/method:
if(isset($_GET['lang']) && $_GET['lang'] == "fr"){
// do something
} else {
// do something else
}
You should also be made aware of (XSS) Cross-site scripting.
Here are a few links to read up on:
http://en.wikipedia.org/wiki/Cross-site_scripting
http://www.sitepoint.com/php-security-cross-site-scripting-attacks-xss/
http://www.smashingmagazine.com/2011/01/11/keeping-web-users-safe-by-sanitizing-input-data/
You can further your research by using "XSS injection php" as keywords in your favorite search engine.
you need to keep the state of the language somewhere.
you will either have to pass it around with each request by
url parameter: page.php?lang=en
path: yourpage.com/en/page.php
or use a cookie to store it. you will get the cookie value passed with each server request
you can read the cookie through the $_COOKIE var. you can set it either in javascript or php
Personally, I recommend an on click for your language selector that will create a new PHP session and store the language.
The benefit of doing it this way is that you don't always have to have your language appended to the end of your URL. This will only happen each time a session has to be created, (so if you don't set a timeout then only when the computer restarts). Once the page redirects from the page that sets the language it doesn't have to $_GET anymore, but rather just check for an active session.
You will have to redirect the user to the page that has your PHP script and then set the language based on the what is sent in the URL. You could however, redirect after the script finishes back to the page the user was on (and load their new selected language).
HTML:
Français
English
PHP:
// intitially set language by your selector
<?php
session_start();
$_SESSION['language'] = $_GET['lang'];
?>
Now you could place your getter code on any page that gets included on all your pages (like a header or base page):
// check for the language
<?php
session_start();
if (isset($_SESSION['language'])) {
// now change the language of the page based on what it is
if ($_SESSION['language'] == "en") {
// change page language to english
} else {
// change page language to french
}
}
?>
It looks like you are using you are using a function called get_lang_id() to pull from the cookie and use that to load the language file.
The get_lang_id() function is currently defaulting to English:
function get_lang_id()
{
return ( isset( $_COOKIE['lang'] ) &&
strlen( $_COOKIE['lang'] ) == 2 &&
is_language_supported( $_COOKIE['lang'] ) ) ?
htmlspecialchars($_COOKIE['lang']) : 'en';
}
If you change the 'en' at the end to 'fr', it will change the default language file to the French version. Clicking either link will set a cookie, which will skip using the default.
In an php-based application I've been coding, I have the following small block of code:
if (isset($_SERVER['QUERY_STRING'])) {
header("Location: " . $_SERVER['QUERY_STRING']);
}
In my application, I use framesets and frames. This code is present in the main content area frame, and upon execution in IE, creates an infinite loop which kills the browser unless I manually stop loading.
The purpose of this code is to detect if there is a query string appended to the url, and if so, redirect to that query string. I've primarily been developing using chrome and and firefox, and today decided to test it in IE9. I have not tested it in any previous versions, but so far this behavior only occurs in IE, and I'm frankly stumped on why such is happening. I've searched for similar questions here and on the internet, but so far no dice.
Edit
As I noted with an earlier edit, I am using framesets and frames to control the interface. The left-hand frame, a side bar, contains links with a base target of the main 'content' area frame. The content of the content area frame contains javascript that appends a query string to the parent window's url, so that when the index page is visited(with the query string present), it will redirect the content frame to that specific page.
This works perfectly fine in Chrome. Not IE(or firefox, which I just discovered as of this edit). Ie instead redirects to the index page, the page containing the frameset, and it does this forever, creating sidebar after sidebar.
Try the following:
session_start();
if ( !isset($_SESSION['Redirect'] ) && isset( $_SERVER['QUERY_STRING'] ) ) {
$_SESSION['Redirect'] = true;
header( "Location: " . $_SERVER['QUERY_STRING'] );
}
I don't know if this can be your problem at all, but as per HTTP/1.1, redirection requires the full absolute path including the hostname. So perhaps try this:
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = $_SERVER['QUERY_STRING'];
header("Location: http://$host$uri/$extra");
exit;
?>
Or another suggestion is to avoid using the full querystring (like ?thispage.php), but to use a GET parameter instead (like ?path=thispage.php).
<?php
/* Redirect to a different page in the current directory that was requested */
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = $_GET['page'];
header("Location: http://$host$uri/$extra");
exit;
?>
I kind of hate myself for not thinking of this sooner, given how horribly simple it is. All I did, was check if $_SERVER['QUERY_STRING'] was empty, as so:
if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') {
header("Location: " . $_SERVER['QUERY_STRING']);
}
And that solved the problem of the index page creating infinite nested framesets and frames.
I have a page with links that looks like this:
...
I also may have a GET variable ?lang=en in the current url. How can I add the GET variable ?lang=en to all the links from the page, without adding them manually or adding a variable to each link? Thanks.
set $_ENV['lang'] = 'en' in your basic ( assume config.php ) file
and retrieve by
getenv('lang') or $_ENV['lang']
Refernece
Add lang=en to session variable as $_SESSION['lang']='en' & initialized it in every page.
You could use output buffering or an Apache filter to parse your output to automatically add the lang query string parameter to all links, however, this isn't terribly efficient.
If you really do not want to add it manually to each link then I suggest you store it in a session variable.
At the start of each page (perhaps in a generic include script) you could have something like:
<?php
define('DEFAULT_LANG', 'en_GB');
session_start();
// check if a new lang has been specified.
if (isset($_GET['lang'])) {
// yes, so use the requested lang
$_SESSION['lang'] = $_GET['lang'];
// otherwise, check if a lang was previously set
} else if ( ! isset($_SESSION['lang']) ) {
// no, so use default lang:
$_SESSION['lang'] = DEFAULT_LANG;
}
?>
You should then use $_SESSION['lang'] instead of $_GET['lang'] in the rest of your page. Also, you may want to add some sort of validation to ensure the requested lang is valid and available.
I have a little problem with redirecting. Registered users follows this link site.com/reg.php?passkey=1234 but the first the user get redirected to the correct language based on a cookie. I need to keep the passkey variable when the user is redirected. like this ?lang=en_US&passkey=1234
My code so far look something like this:
if (!isset($_GET['lang']))
{
if (isset($_COOKIE['country']))
{
$country = $_COOKIE['country'];
(...)
elseif ( $country == "US" ){
$variables = $_GET;
$variables['lang'] = "en_US";
header('Location: ?' . http_build_query($variables));
exit();
}
This works:
reg.php
reg.php?lang=en_US
reg.php?lang=en_US&passkey=test
reg.php?passkey=test&lang=en_US
but this gives an The page isn't redirecting properly error
reg.php?passkey=test
I don't understand why this doesn't work when all the other combinations seem to work perfectly.
The HTTP 1.1 Specification requires that the location needs to be a Absolute URI
(See RFC2616 14.30 Location)
The location header('Location: ?' . http_build_query($variables)); does not contain an absolute URI.
You need something like:
header('Location: /folder/file.php?'.http_build_query($variables));
If you need to do this on different locantions you can use $_SERVER['PHP_SELF'] to set the current file as redirect location. For example
header('Location: '.$_SERVER['PHP_SELF'].'?'.http_build_query($variables));
I think, you should change the http_build_query($variables) to http_build_query($variables, null, '&')
I hope my answer is useful.
I have a website authored in PHP where any time a user receives an error I will redirect them to a another page (using header(Location:...)) and put the error ID in the URL so that I know which error to display.
E.g. If the user tries to access a product page but that item is no longer available I will redirect back to the category of items they were previously looking at and display an error based on the error ID I have specified in the URL.
www.example.com/view_category.php?product_category_id=4&error_id=5
There are two things I don't like about this approach:
It displays the error_id in the URL.
if the page is refreshed, the error will still display.
Is there a way to cleanly remove a specific $_GET variable from a URL while leaving the rest of the variables intact AFTER the page is loaded?
I'm thinking maybe it's using modRewrite or a redirect back to the page itself but removing the error_id from the URL or using a $_SESSION variable and avoiding putting the error_id in the URL. Your thoughts?
I really am learning a lot from this community and thought if I posed the question I might be able to learn something new or to get some varied ideas as I'm fairly new to scripting.
No, there's no way to do that explicitly - at least not without a page refresh but then you'd lose the data anyway.
You're better off using a temporary session variable.
if ( /* error condition */ )
{
$_SESSION['last_error_id'] = 5;
header( 'Location: http://www.example.com/view_category.php?product_category_id=4' );
}
Then, in view_category.php
if ( isset( $_SESSION['last_error_id'] ) )
{
$errorId = $_SESSION['last_error_id'];
unset( $_SESSION['last_error_id'] );
// show error #5
}
Yes, there is a way to remove especific $_GET from PHP...
varToRemove = "anyVariable";
foreach($_GET as $variable => $value){
if($variable != varToRemove){
$newurl .= $variable.'='.$value.'&';
}
}
$newurl = rtrim($newurl,'&');
Then, put the $newurl in the link.. like this:
pageurl?something=something&<? echo $newurl; ?>
I know it´s an old post, but, other programers may be search for it!
First, log the error in your database :)
After that, set a cookie or session variable and then redirect the user to safe page. When that page is loaded, have it check for the variable, display the error, and then delete variable from the cookie or session array.
One way is to compare the HTTP_REFERER with the SCRIPT_NAME. They'll be the same if the user has hit Refresh.
Quick Hack: You could have also imploded()'d on "&" in the the $_SERVER['QUERY_STRING'] variable to manipulate that string and then explode()'d it back.
Wouldn't this approach work?
<?php
$params = array_diff($_GET, array("variable_name" => $value));
$new_query_string = http_build_query($params);
?>
<script>window.history.pushState('verify_email', 'Verify Email', '?<?php echo $new_query_string; ?>');</script>
i had same problem
try : http://www.azazia.com/kb/entry/26/
if (!empty($_GET['passvar'])) {
unset($_GET['passvar']);
echo "<META HTTP-EQUIV=\"refresh\" CONTENT=\"0; URL=".$_SERVER['PHP_SELF']."\" >";
}
work perfectly for me.