When users enter my site for the first time they are asked to select a location, this determines their currency. When selected, the country code is stored in $_SESSION['countryCode']and displayed onscreen.
However I'd also like to have this reflect in the URL, for instance if the user selected Germany the url would redirect to http://test.com/de/. Additionally I'd also like it if the user typed the above URL then when the page loads for it to set the session as 'de'.
I'm not sure where to start with this I presume we'd have to do a url rewrite within the htaccess file but I don't know how this would interact with the php session, so any help would be thoroughly appreciated.
All the best,
Matt
You would want to store your country session globally and then reference it in your header/bootstrap file.
I would personally run a switch statement to determine how URLs are structured with a default to GB.
session_start();
// Assuming your country has come in from a validated form post.
$urlBit = $_POST['country'];
switch($urlBit) {
case 'de':
$country = $urlBit;
break;
case 'es':
$country = $urlBit;
break;
default:
$country = 'gb';
break;
}
$_SESSION['country'] = $country;
Regarding the vice-versa, you could write some code to put the URL into a string and look for '/de/', '/gb/' within the string.
Again, I would revert back to a switch statement to handle that and once you know your result. Then, store it all using $_SESSION['country'].
session_start();
// Assumed URL structure.
$url = 'http://www.website.com/de/';
// The switcheroo.
$urlParts = explode('/', $url);
$urlBit = $urlParts[3]; // Returns 'de'
// The same switch as above. Stick it in a function or class/method, maybe.
switch($urlBit) {
case 'de':
$country = $urlBit;
break;
case 'es':
$country = $urlBit;
break;
default:
$country = 'gb';
break;
}
$_SESSION['country'] = $country;
This is the best answer I can offer without seeing code first, but this simple logic would solve your issue, assuming you knew how to implement the above.
You could easily do this without htaccess but it's hard to say without seeing your code.
You can do this without .htaccess.
Create a lang file that you include in all your script. That lang file will have a variable generated from your session variable that will be appended to all your links and it will have the carrying the currency code
initially at a login then cuntry is located by gps. then depending on the cuntry u write the php code like as.initially u defind the cuntry currency values..
use case or if condition
for select currency cuntry
like as
switch($cuntry_name)
{case(germany):
$_SESSION['countryCode'] = 'de';
break;
case(...):
$_SESSION['countryCode'] = '..';
break;
}
Related
I am somewhat a newby at PHP ... so what im trying to do is to get the the page using the following code
<?php include $_GET['topic']; ?>
to get the url like this http://ulixtxteditor.org/entities/helpCentre?topic=credits
that much works great for me however if no page is found i would like to use the else statement to display an error instead of a blank page. What should I do? ex: http://ulixtxteditor.org/entities/helpCentre?topic= so this part would display an error?
<?php if(isset){include $_GET['topic'];} else {echo "error"} ?>
I tried this but it wont work.
Use something like this:
<?php
// In case topic parameter wasn't provided you will have fallback.
$topic = isset($_GET['topic']) ? $_GET['topic'] : '';
// Now you can check topic and have valid file name.
switch ($topic) {
case 'credits':
$fileName = 'credits.php';
break;
default:
$fileName = 'index.php';
break;
}
// Now it is possible safely include file.
include __DIR__ . DIRECTORY_SEPARATOR . $fileName;
Using $_GET['topic'] directly in include or require construction is unsafe because you vulnerable to "Directory traversal attack". Moreover you always must validate input parameters with purpose avoid include in php script css files etc...
<?php include $_GET['topic']; ?>
Don't do that. It creates a massive and easily-exploited security vulnerability.
For example:
?topic=index.php -- creates an infinite loop
?topic=/etc/passwd -- displays sensitive data from the server
?topic=/proc/self/environ -- executes code from the process environment. This will frequently include user-controlled data like the values of HTTP headers, allowing for remote code execution.
Your site will be exploited if you implement this. There are numerous bots which scan public web sites for this vulnerability, many of which will attempt to exploit it automatically upon detection.
If you want to include a file based on the value of a GET variable, use switch($_GET['topic') to define the acceptable values of that variable. This will also allow you to implement error handling as a default: clause.
This is a fairly common way of implementing a simple junction box/router. Use a switch statement.
$topic = isset($_GET['topic']) ? $_GET['topic'] : '';
switch ($page) {
case 'credit':
case 'otherpage':
case 'otherpage2':
require_once(dirname(__FILE__) . '/' . $page . '.php');
break;
default
require_once(dirname(__FILE__) . '/' . 'default.php');
}
You whitelist your pages/topics by adding a case statement at the top for each, and anything that doesn't match or have a page is processed by loading the default page.
In this example, I assume all the topic pages are in the same directory as this script (typically named index.php).
I'm searching now for hours. I try to switch the store language after the login.
Given is:
The id of the Store I want to switch too.
The Event Observer is also done.
This is what I worked out the last hours
My Observer:
$customerId = Mage::getModel('customer/session')->getCustomer()->getId();
// Get the Store ID we want to switch too
$connection = Mage::getSingleton('core/resource')->getConnection('distributor_read');
$mainLanguage = $connection->fetchAll('SELECT...');
$storeId = $mainLanguage[0]["store_id"];
if (!$storeId == null) {
$storeCode = Mage::app()->getStore($storeId)->getCode();
// Here I have to switch by the store code
return;
}
Would be glad if someone could help me out.
At least I need a method to switch the language or storeview, but I don't find any working MagentoAPI methods.
to Set the store id programatically
In the index.php file, (in your language specific folder), add the following:-
$store_id = 'your_store_id_here';
$mageRunCode = 'store view code';
$mageRunType = 'store';
Mage::app()->setCurrentStore($store_id);
Mage::run($mageRunCode, $mageRunType);
I am suggesting you to create some temporary session variable from login action and read in index.php to set language pack and again unset it if your work has been done
Hope someone will find this information useful :)
I will tell you guys what I did for this case. I tried to get the Mage_Core_Controller_Response_Http class, completely in vain.
So I kept going on my research and I found a solution.
I used:
header('Location: '. Mage::app()->getStore()->getBaseUrl().'/customer/account?___store='.$storeCode);
There we go, my on login observer just set the language.
edit:
To set a new header could cause some problems, because if just any piece of html is already rendered you can not set a new header.
I worked sth. else out:
$url = Mage::getUrl('*/*');
$url .= "?___store=" . $storeCode;
$response = Mage::app()->getFrontController()->getResponse();
$response->setRedirect($url);
$response->sendResponse();
exit();
There is obviously still a problem, the exit shouldn't used in good software code, but a simple return does not work, it does not end or kill the observer action.
I still working on a solution to kill the observer in a right way. As I said the observer need to get killed to redirect the url.
Sorry for a noob question. I have my php script organized like this:
switch(true)
{
case (isset($_POST['login'])):
// ...some code to check a login
break;
case (isset($_POST['register'])):
// ... some script to register a new user
etc.
Access to each section of code is controlled by using the name of the submit buttons in forms. I borrowed a menu system that uses URL's with command parameters instead of submit buttons. An example URL looks like this:
http://MYIPADDRESS/gradebook/login.php?guid=51913a6e37e1b&command=newclass
So, to get the same control of the program flow using URL's I tried adding this at the beginning of the file:
if (isset($_GET['command']))
{
switch ($_GET['command'])
{
case 'newclass':
$_POST['basicsettings']='basicsettings';
$guid=$_GET['guid'];
break;
case 'logout':
$_POST['logout']='logout';
break;
case 'continue':
$guid=$_GET['guid'];
$_POST['continue']='continue';
break;
}
}
This doesn't work because the $_GET global array is only reset if the next operation issues a new URL, and in most cases the user would use a submit button on a form and not select another menu item. You can't use unset on $_GET within a php script because it only affects the local copy. I tried setting up a $_SESSION command variable instead and refreshing the page using header("Location:login.php") to reset the $_GET global array but this also didn't work. Here is the modified code:
session_start();
if (isset($_GET['command'])) // if program flow control came from a URL
{
switch ($_GET['command']) // check which script section to use
{
case 'newclass':
$_POST['basicsettings']='basicsettings';
$guid=$_GET['guid'];
$_SESSION['command']='basicsettings';
$_SESSION['guid']=$guid;
header("Location:login.php");
break;
case 'logout':
$_POST['logout']='logout';
$_SESSION['command']='logout';
header("Location:login.php");
break;
case 'continueteacher':
$guid=$_GET['guid'];
$_POST['continueteacher']='continueteacher';
$_SESSION['command']='continueteacher';
$_SESSION['guid']=$guid;
header("Location:login.php");
break;
}
}
if (isset($_SESSION['command']))
{
$var=$_SESSION['command'];
$_POST[$var]=$_SESSION['command'];
$guid=$_SESSION['guid'];
$_REQUEST['guid']=$_SESSION['guid'];
unset($_SESSION['command']);
}
switch(true)
{ .. ...etc.
I realize that one way to fix this is to change the menu system to use submit buttons instead of URL's, but that has some downsides as well. Is there any way to make this work? Assuming you can see what I'm trying to do and it makes sense?
The code below ensures that when a user accesses control panel, they are ran through a quick verification process to validate what their entities are. For instance, if a user is level 1 they are only given access to video feed which means nothing else is available to them.
When I look at the code though, I can see video feed being called when case 1 and 3 are called. I would possibly enjoy an alternative to make the code more efficient.
I was told a possible array could make things a little easier but then again this is faster.
switch ($_SESSION['permission']) {
case 1: // Level 1: Video Feed
include ("include/panels/videofeed.index.php");
break;
case 2: // Level 2: Announcements / Courses / Teachers
include ("include/panels/announcements.index.php");
include ("include/panels/courses.index.php");
include ("include/panels/teachers.index.php");
break;
case 3: // Level 3: Announcements / Video Feed / Courses / Teachers / Accounts / Logs
include ("include/panels/announcements.index.php");
include ("include/panels/videofeed.index.php");
include ("include/panels/courses.index.php");
include ("include/panels/teachers.index.php");
include ("include/panels/accounts.index.php");
include ("include/panels/log.index.php");
break;
case 4: // Level 4: Teachers
include ("include/panels/teachers.index.php");
}
It's fine the way it is. I think you don't mean "efficiency" when you refer to the "repeated" includes. You mean you could compact your code by using the switch fall-through.
While this might make your code smaller, it has no significant impact of efficiency (the time the script takes to run) and it will actually make the code harder to read. Leave it be.
Frist you may run better if you use require_once if its possible.
The second point is to shorten the url it seems that its every include the same.
Maybe try to use it in a function for example:
$permission_id = $_SESSION['permission']
function requireModule($moduleName, $path = 'include/panels/') {
$moduleName .= '.index.php';
require_once($path . $moduleName);
}
// if you want you can add an arry for it:
$permissionModules = array(
array('videofeed'),
array('announcements', 'courses', 'teachers'),
array('announcements', 'courses', 'teachers', 'accounts', 'log', 'videofeed'),
array('teachers')
);
// now we can put it in a more effectiv way
if(array_key_exists($permission_id, $permissionModules)) {
foreach($permissionModules[$permission_id] as $includes) {
requireModule($includes);
}
}
Wrong ? Correct me!
I'm just looking for some advice. I'm creating a website that offers (at least) 2 languages.
The way I'm setting it up is by using XML files for the language, PHP to retrieve the values in the XML nodes.
Say you have any XML file, being loaded as follows:
<?php
$lang = "en";
$xmlFile = simplexml_load_file("$lang/main.xml");
?>
Once the file contents are available, I just output each node into an HTML tag like so:
<li><?php echo $xmlFile->navigation->home; ?></li>
which in turn is equal to : <li>Home</li>
as a nav bar link.
Now, the way in which I'm switching languages is by changing the value of the "$lang" variable, through a "$_POST", like so:
if(isset($_POST['es'])){
$lang = "es";
}elseif(isset($_POST['en'])){
$lang = "en";
}
The value of the "$lang" variable is reset and the new file is loaded, loading as well all the new nodes from the new XML file, hence changing the language.
I'm just wondering if there is another way to reset the "$lang" variable using something else, other than "$_POST" or "$_GET". I don't want to use query string either.
I know I could use JavaScript or jQuery to achieve this, but I'd like to make the site not too dependable on JavaScript.
I'd appreciate any ideas or advice.
Thanks
I would go for session variable.
At the beginning of your pages you'll have:
if (!isset($_SESSION['language']))
$_SESSION['language'] = "en";
Then you'll have some links to change the language
Español
Français
Changelanguage.php simply is something like
$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect
Have you thought about using $_SERVER["HTTP_ACCEPT_LANGUAGE"]? Something like this:
if ($_SERVER["HTTP_ACCEPT_LANGUAGE"]) {
$langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
for ($i = 0; $i < count($langs); $i++) {
if ($langs[$i] == "en") {
$lang = "en";
break;
}
elseif($langs[$i] == "es") {
$lang = "es";
break;
}
}
}
Of course, a switch statement might fit a bit better here, and there's more ways to say English than only en, but this should work without the user having to do a thing. If they manually change, store it in a cookie as per Ben's answer.
The most common way would be to use it as part of the url and extract it when a page loads:
http://www.your-site.com/en/somepage
Are you using a framework?
The most common way to pass a language identifier is subdomain.
http://en.wikipedia.com/
both subdomains should point to the same directory and actual language can be easily extracted from the HTTP_HOST
and for storing language files the solution is gettext