Using a link and submit button to submit a form - php

I am working on a website. I would like the website to redirect from index.php to index.php?lang=En.
This is because the site is multi-lingual and the default language needs to be set to English on the home page. I used the header() method to do this but that causes a redirect loop as the site keeps reloading forever.
How can I overcome this barrier?

In your PHP:
<?php
// Default to English if $_GET['lang'] isn't set
$lang = isset($_GET['lang']) ? $_GET['lang'] : 'En';
// If language not in array of available languages, reset to English
if (!in_array($lang, array('En', 'Es', 'Fr'))) {
$lang = 'En';
}
header('Location: index.php?lang=' . $lang);
?>
In your HTML:
English,
Español,
Français

I would do like this:
if(!isset($_GET['lang']) {
header('location: http://www.example.com/index.php?lang=En');
}

Check if the lang parameter exists in the URL, and do the redirect only if it doesn't:
if (!isset($_GET['lang']) {
header('Location: http://www.example.com/index.php?lang=En');
}

Related

How to keep some of the values of $_SESSION array after session_destroy()?

I use $_SESSION array to save the language of my website and It works fine but I found lately some problem when I log out of my website I use this code :
<?php
if (isset($_SESSION['logged_in']))
{
session_destroy();
header('Location: ./index.php');
}
?>
So when I logout the $_SESSION['lang'] variable is destroyed and the website language go back to default so I did this :
<?php
if (isset($_SESSION['logged_in']))
{
$lang = $_SESSION['lang'];
session_destroy();
$_SESSION['lang'] = $lang;//if I echo this $_SESSION['lang'] I get the website language but after header('Location: ./index.php'); it still deleting the lang variable
header('Location: ./index.php');
}
?>
Is there something I could do it here to keep the value ???
Save this value in cookies(if it doesn't contains sensible information).

PHP URL for my homepage

so I'm editing a PHP site (I'm a Python guy). What I need is a way to maybe redirect such that when someone navigates to the site e.g. www.mysite.com, the homepage should be served. The system used to serve other pages is as sush: to navigate let's say to the contacts page, we use www.mysite.com?page_id=contact-us. The query string helps the server side code to know what page to serve. So what I want is that when a user navigates to the site by typing www.mysite.com, he should get to the page www.mysite.com?page_id=home.
Thank you.
Sample code:
$page = isset($_GET['page_id']) ? $_GET['page_id'] : null;
if ($page !== null) {
//redirect to correct page
require("modules/inside.php");
} else {
//redirect to 'home'
header('Location: https://www.ndovucard.com?page_id=home');
require("modules/home.php");
}
Try...
if (!isset($_GET['page_id'])){
header('Location: www.mysite.com?page_id=home');
}
Something like this?
$page = (isset($_GET['page_id'])) ? $_GET['page_id'] : 'home';
echo $page; // 'home' or provided page_id
From what you've said it sounds like you need a:
if (!isset($_GET['page_id'])) $_GET['page_id'] = 'home';
Personally I prefer a full URL rewrite system rather than passed by URL query as it's believed search engines prefer contact-us.html rather than page_id=contact-us
Edit:
You could alternatively do:
if (!isset($_GET['page_id'])) {
header('Location: /?page_id=home');
die(); // stop any further processing
}
something like:
$page = isset($_GET['page_id']) ? $_GET['page_id'] : 'home';
/* check that page is a valid page else serve error page */
/* then redirect to the correct $page */
header('Location: www.mysite.com?page_id=' . $page);
exit();
By the way, you need some way to check that $_GET['page_id'] is always a valid page_id before redirecting.

Internationalisation with PHP - order of execution of PHP functions

Hey all,
I am trying to internationalise my website with php. I am very new to PHP!
The index.php starts with this:
<?php session_start(); ?>
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
The locale.php looks like this:
<?php
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
} else {
$_SESSION['lang'] = 'en'; // default value
}
// use the necessary language file
include('/locale/' . $_SESSION['lang'] . '.php');
// get phrase from URL
if (isset($_GET["phrase"]))
loc($_GET["phrase"];);
function loc($phrase)
{
global $lang;
if(array_key_exists($phrase, $lang)) {
echo $lang[$phrase];
} else {
echo $phrase;
}
}
?>
The idea is I want to use the function loc($phrase) to get the content either in German or English. But here is the problem:
If I have the code like this, I always get the english version, because in locale.php I can not get the lang from the URL: $_GET['lang'] is undefined. Therefore, the session language is always set to the default language (en).
However, if I move the session_start(); into the file locale.php, the internationalisation works:
index.php:
<?php include 'api/locale.php'; ?>
<html>
<!-- ... -->
<div><?php loc('foo') ?></div>
locale.php:
<?php
session_start();
if(isset($_GET['lang']) {
$_SESSION['lang'] = $_GET['lang'];
// ... rest the same as above
Why is it like this? Am I doing something conceptually wrong? The problem is I am also using this locale.php in ajax calls to get international content for dynamically generated HTML elements:
function loc(phrase)
{
var locString;
$.ajax({
// force synchronous ajax call, to return with locString
async: false,
// url with to be translated id
url: "api/locale.php?phrase=" + phrase,
// "get" for small data (otherwise post)
method: "get",
// callback function after server has reveiced information
success: function (data)
{
locString = data;
}
});
return locString;
}
So if I call locale.php over and over again with this AJAX call, aren't there new sessions starting over and over again? I am not sure if I designed my functions correctly. I am happy about any comments!
Thank you!
=============== EDIT ===============
ok, I tried a new way now:
session.php
// session starts at this point
session_start();
// internationalisation in EN and DE
$allowedLangs = array('en', 'de');
// check lang-parameter given in URL and set language from there
if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs))
$_SESSION['lang'] = $_GET['lang'];
if(!isset($_SESSION['lang']))
$_SESSION['lang'] = 'en'; // default value
locale.php
// include correct languguage file
$root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
include($root . '/locale/' . $_SESSION['lang'] . '.php');
// get phrase from URL and translate it
if (isset($_GET["phrase"]))
{
$phrase = $_GET["phrase"];
global $lang;
if (array_key_exists($phrase, $lang))
echo $lang[$phrase];
else
echo $phrase;
}
both files get included in index.php
<?php include 'api/session.php'; ?>
<?php include 'api/locale.php'; ?>
However, if I locale a phrase with ajax now, the following error message appears:
Notice: Undefined variable: _SESSION in ... /locale.php on line 4
How can that be? I thought $_SESSION is superglobal ?!?
When you call the version of api/locale.php with the session_start via ajax, not a new but the same session will start, which is the correct behaviour.
Word start maybe confusing you but the session start will supply the information of the current session correctly, not a new one. So nothing to worry about.
Also you may consider looking at
$_SERVER['HTTP_ACCEPT_LANGUAGE']
before starting to ajax ping-pong of the server and client for an initial language quick guess...
For the two versions of your code, it is not a mystery why it works when session_start is
in locale.php.
The cause is:
Your ajax call is not entering your script from index.php, it enters directly to api/locale.php.
If you do not session_start in api/locale.php, the ajax call will enter into a sessionless php invocation.
So it will keep the default value since session data is neither can be fetched or can be recorded.
I think there is something conceptually wrong in your locale.php file.
The fact that you always set $_SESSION['lang'] is a bad smell.
There should be a case when you dont set the value of $_SESSION['lang']and just use the value of$_SESSION['lang']without modifying it.
With your locale file as it is , and your ajax call that does not pass 'lang' as a parameter, you will always get the default language.
But anyway your local.php file should start with session_start(); as explained by ishan.
By the way you should not use 'echo' inside your function loc. Instead return the result and do
echo loc('foo');
It would do the same job, but your loc function would be more reusable.
Hi Marcus I will try to answer your question in the comments.
$_SESSION id indeed a super global. But you need to call session_start() for it to works.
That's why it does not work anymore in locale.php
The problem is that your locale.php file is serving two purposes at the same time.
It should just translate but not be reachable directly from an url.
So you should do something like this :
session.php
`
//here you define a default value. So whatever happens, you know that $_session['lang']
//will always be set.
if(! isset ($_SESSION['lang'] {
$_SESSION['lang'] = 'en'; // default value
}
// internationalisation in EN and DE
$allowedLangs = array('en', 'de');
// check lang-parameter given in URL and set language from there
//if necessary, the default value will be overwritten.
if(isset($_GET['lang']) && in_array($_GET['lang'], $allowedLangs)) {
$_SESSION['lang'] = $_GET['lang'];
}
`translate.php
function getTranslation ($phrase, $lang='en') {
$root = realpath($_SERVER["DOCUMENT_ROOT"]) ;
include($root . '/locale/' . $lang . '.php');
//the array with the phrases and their translations should not be called $lang
//to avoid confusion. Let's call it $translations
if (array_key_exists($phrase, $translations))
return $translations[$phrase];
else
return $phrase;
}
}
locale.php
`
This file is to be called in ajax.
It will works providing $_SESSION['lang'] as already been defined
(in index.php for example). Otherwise you fall back to the default lang.
include 'path_to_translate/translate.php';
session_start();
if(isset($_SESSION['lang'] {
$lang = $_SESSION['lang'];
} else {
$lang = 'en';
}
$phrase = $_GET['phrase'];
echo getTranslation($phrase, $lang);
index.php
session_start();
include 'api/session.php';
include 'path_to_translate/translate.php';
$lang = $_SESSION['lang'];
<some html>
//to translate anything
<?php echo getTranslation($anything, $lang) ?>
</some html>
Hope this will help. Off course I can not test all this code , so their might be some mistake. But that's the general idea.
I tried not to change to much what you' have done. But there is still a problem. You should not define the lang in index.php. If there is a form in your index to choose the lang. Make a call in ajax to set_lang.php. It is not for the index to set the lang in session.

Php for a bilingual site

Is it possible using php, for a user to click on a english/french toggle button, that would then read the current url, and match it to the french version of the page?
Thank you for your time.
When the users clicks the button, populate a session variable with the selected language:
session_start();
$_SESSION['language'] = 'FR'; // Or 'EN', etc
Then use templates to store your language-specific information. When you load the template, include the language code
// Load a template
Template::load( '<page_name>', $_SESSION['language'] );
// Where the `load()` method looks something like this:
public function load( $page_name, $language ) {
// Construct the path to the template
$file_handle = fopen( PATH_TO_TEMPLATES . $language . "/" . $page_name );
// Do something with the template here.
}

PHP problems with multilanguage

I have problems with php multilanguage. I'm using function *check_lang* and it works fine in one page, but once I go to another page the $_SESSION['lang'] variable $lang turns back into default (en). What is the problem?
<?php
function check_lang() {
if(isset($_GET['lang'])
{
$lang = $_GET['lang'];
$_SESSION['lang'] = $lang
}
if (!isset($_SESSION['lang'])) {
$lang = 'en';
} else {
$_SESSION['lang']=$lang;
}
//directory name
$dir = 'languages';
return "$dir/$lang.lng";
}
?>
You have to:
session_start();
At the top of each of your scripts in which you want to use session variables.
You need to call session_start() on each page you're planning on using the $_SESSION[] global in. That's what tells PHP that it should look up the session_id from the user's cookies or the query string so that PHP knows which session's values to use.
Reference.

Categories