There is a session variable called 'locale' with value: en.
$locale = session()->get('locale'); // value = 'en';
And there is an object $page with attributes: content_en, content_ru, content_de.
All I need is to echo $page->content_en or $page->content_ru or $page->content_de, but depending on locale.
echo $page->content_'.session()->get('locale').';
Here's a more complete solution that you can even run on phpfiddle.org
$page = new stdClass();
$page->content_en = 'Testcontent';
$page->content_de = 'Testinhalt';
$property = 'content_' . locale("en");
if(property_exists($page, $property)) {
// The property exists, print it!
echo $page->$property;
} else {
// Fallback to some default
}
function locale($loc)
{
return $loc;
}
You won't be able to access a property via a combined string.
The only option you have is to first put it in a string, and use that variable as a property access.
$property = 'content_' . session()->get('locale');
if( isset($page->$property) ) {
echo $page->$property;
}
Fabian's answer is more flexible and generally better. However, here's an alternative approach if you only accept specific values.
Using if
$locale = session()->get('locale'); // value = 'en';
if ($locale == "en") {
echo $page->content_en;
} elseif ($locale == "ru") {
echo $page->content_ru;
} elseif ($locale == "de") {
echo $page->content_de;
}
Using switch
$locale = session()->get('locale'); // value = 'en';
switch ($locale) {
case "en":
echo $page->content_en;
break;
case "ru":
echo $page->content_ru;
break;
case "de":
echo $page->content_de;
break;
}
This should do it:
echo $page->{'content_' . session()->get('locale')};
Related
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
If in your $data array there is one car and one location then you can do the following to save the variables and use them later:
$loc_name = '';
$car_name = '';
foreach ($data as $key => $value) {
if ( is_special_car($value['name']) )
continue;
switch ($type) {
case 'car':
$car_name = $name;
break;
case 'location':
$loc_name = $name;
break;
default:
break;
}
if($loc_name && $car_name){
//You have a car and loc name now
}
}
If your $data array is different you will have to modify the code of course, maybe resetting the $loc_name and $car_name when you've done whatever you needed to after getting them.
I've figured out how to do this. I've passed the location name as a 3rd argument from the show_data_inline_location back on location.php back to the function by including the location name as follows:
show_data_inline_city($data['Cars_In_Location'], 'car', $data['Name']);
Then in the function itself I have done added the following argument:
function show_data_inline_location($data, $type, $location_name)
And added this to create a URL friendly string:
$loc_name = strtolower(str_ireplace(" ","-", $location_name));
Then echoing this:
echo '<a href="'.$link_url.$name.'-in-'.$loc_name.'"><div class="overlay">'.PHP_EOL;
This way I don't need to seperate the case in the switch, only need to use this for the difference between 'car' and 'location':
if ($type == 'car') { echo 'this'; }
if ($type == 'location') { 'that'; }
Thanks for all of your help.
I have 4 parameter in my URL. I retrieve the url parameter from my url that is given. With every parameter I'm changing the path to a directory and get different images.
My sample url look like this:
www.sample.com?cat=section1&language=de&prices=pl
The code is working but it's a spagheti code.
Is there a solution to make is less DRY ? How do I retrieve multiple url parameter ?
if(isset($_GET["cat"])) {
switch ($cat) {
case 'section1':
if(isset($_GET["language"])) {
$language = htmlspecialchars($_GET["language"]);
if($language == "de") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/dp/low/*.jpg');
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
}
elseif ($language == "en") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/ep/low/*.jpg');
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
else {
$files=glob('pages/section1/en/low/*.jpg');
}
}
elseif ($language == "cz") {
if(isset($_GET["prices"])) {
$prices = htmlspecialchars($_GET["prices"]);
if($prices == "pl"){
$files=glob('pages/section1/cp/low/*.jpg');
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/cn/low/*.jpg');
}
}
else {
$files=glob('pages/section1/dn/low/*.jpg');
}
break;
case 'section2':
//the same like in section 1, path is .../section2/...
break;
case section3:
//the same like in section 1, path is .../section3/...
break;
default:
//the same like in section 1
break;
}
else {
//the same like in section 1
}
The path d=german, e=english, c=czech, p=prices, n=noprices
You could shorten/remove many if else statements with just doing the checks:
$lang_code = $language[0];
There you have your first letter, you can do the same with every GET parameter.
So you can use that as in:
$files=glob('pages/section1/'.$lang_code.'p/low/*.jpg');
You can do the same for everything else.
P.s.: don't forget to sanitze any user input i.e.:
$language=mysqli_real_escape_string($conn, $_GET['language']);
I'd probably do something like this:
<?php
$allowedCat = ['section1', 'section2'];
$allowedLanguage = ['pl', 'en', 'cz'];
$allowedPrice = ['pl', '??'];
$cat = (isset($_GET["cat"])) ? $_GET["cat"] : null;
$language = (isset($_GET["language"])) ? $_GET["language"] : null;
$prices = (isset($_GET["prices"])) ? $_GET["prices"] : null;
if (!in_array($cat, $allowedCat)) throw new \Exception('Invalid `cat`');
if (!in_array($language, $allowedLanguage)) throw new \Exception('Invalid `language` option.');
if (!in_array($prices, $allowedPrice)) throw new \Exception('Invalid `price` option.');
$someVar1 = ($prices === 'pl') ? 'p' : 'n';
$someVar2 = $language[0];
$files = glob("pages/{$cat}/{$someVar1}{$someVar2}/low/*.jpg");
Think that should be self explanatory. Translates one to one really. Was not certain on how the other price option was specified...
Hi this is my code to do some basic navigation. No matter what i do, when i pass parameter "stranky", it always prints "first else". I have also tried array_key_exist function, also with no luck. Any ideas?
if(isset($_GET["stranka"])) {
$page = $_GET["stranka"];
$povoleneStranky = array("vsichni", "vecery", "pridej_vecer", "uprav_index");
if (isset($povoleneStranky[$page])) {
$stranka = "$page.php";
include $stranka;
echo $page;
} else {
include ('vsichni.php');
echo "first else <br>";
}
else {
include ('vsichni.php');
echo "second else";
}
You can reduce the code to :
$povoleneStranky = array("vsichni", "vecery", "pridej_vecer", "uprav_index");
if (isset($_GET["stranka"]) && in_array($_GET["stranka"], $povoleneStranky)) {
$stranka = $_GET["stranka"] . ".php";
include $stranka;
echo $_GET["stranka"];
} else {
include ('vsichni.php');
}
Check if this is working.
SOLUTION 2 - More Optimized One:
$povoleneStranky = array("vsichni", "vecery", "pridej_vecer", "uprav_index");
$stranka = 'vsichni.php';
if (isset($_GET["stranka"]) && in_array($_GET["stranka"], $povoleneStranky)) {
$stranka = $_GET["stranka"] . ".php";
}
include $stranka;
The array has no "string" indexes/keys, only numeric and the items inside it are all string values, so using in_array() is the better way to check.
if (isset($povoleneStranky[$page])) {
should be
if (in_array($page, $povoleneStranky)) {
...unless $_GET["stranka"] has a numeric value, in which case my answer is invalid.
the issue is that you are useing array $povoleneStranky = array("vsichni", "vecery", "pridej_vecer", "uprav_index");
this array is somethig like this in php array([0]=vsichni[1]=>vecery[2]=>pridej_vecer[3]=>uprav_index);
so you can so it always return run else because it never finds $povoleneStranky[$page] you can try isset($povoleneStranky[0])
First of all close parantheses
if(isset($_GET["stranka"])) {
$page = $_GET["stranka"];
$povoleneStranky = array("vsichni", "vecery", "pridej_vecer", "uprav_index");
if (isset($povoleneStranky[$page])) {
$stranka = "$page.php";
include $stranka;
echo $page;
} else {
include ('vsichni.php');
echo "first else <br>";
}
}
else {
include ('vsichni.php');
echo "second else";
}
Because right now like someone said you can not have 2 else.
Also var
$povolenestranky
is not in your case mulidimensional array and you trying to get
$povolenestranky[$page]
wich not exist if page is a string.
I want to write a simple if statement using HTTP_ACCEPT_LANGUAGE function that redirects based on result of what the users browser language is. I am still a beginner so am obviously keeping it as simple as possible. This is what I have so far but the "if" statement needs work. Can anyone help me with a fix?
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ($lang=german) {
header("Location: http://www.example.com/german/index.html");
} else if ($lang=spanish) {
header("Location: http://www.example.com/spanish/index.html");
}
else if ($lang=french) {
header("Location: http://www.example.com/french/index.html");
}
else if ($lang=chinese) {
header("Location: http://www.example.com/chinese /index.html");
} else {
echo "<html>english content</html>";
}
?>
I don't know what your language literals are, so I'd say make them ISO language codes.
Use a switch statement, this is more readable and smaller:
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
switch($lang) {
case "de-DE":
case "es-ES":
case "cn-CN":
case "fr-FR":
header("Location: http://www.example.com/$lang/index.html");
break;
default:
header("Location: http://www.example.com/en-US/index.html");
break;
}
Further, you are assigning, not comparing. You compare with ==:
if ($lang == "de-DE")
Assuming you always redirect to /language/, you could do it this way:
<?php
$lang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
if ( in_array( $lang,array("german","spanish","french","chinese") ) ) {
header("Location: http://www.example.com/$lang/index.html");
} else {
echo "<html>english content</html>";
}
?>
Also, the comparisons in your if need to be done with ==, it's assignment otherwise!
Try this:
<?php
$path = array(
'en-US' => 'english',
// etc
);
$accepts = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
if (in_array($accepts[0], $path)) { // if path exists for language then redirect to path, else redirect to default path (english)
header('Location: http://www.example.com/' . $path[$accepts[0]] . '/index.html');
} else {
header('Location: http://www.example.com/english/index.html');
}
?>
HTTP_ACCEPT_LANGUAGE returns not "english", but two signs symbol like "en", or region and language symbol like "en_us". You shouldn't use if statement it's hard to read. You should use array (in future you can simple write it to config files, or move to databases).
The proper code should look that:
$default_lang = 'en';
$lang_redirectors = array('de' => 'http://www.example.com/german/index.html',
'en' => 'http://www.example.com/english/index.html');
function redirect($url){
header("Location: " . $url);
}
$hal = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$langs = explode($hal, ',');
foreach($langs as $lang){
$lang_prefix = substr($lang, 0, 2);
if(in_array($lang_prefix, $lang_redirectors)){
redirect($lang_redirectors[$lang_prefix]);
break;
}
redirect($lang_redirectors[$default_lang]);
}
<?php
$browserlang = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
$lang = $browserlang[0] . $browserlang[1] . $browserlang[2] . $browserlang[3] . $browserlang[4];
if (($lang=="sk_SK") OR ($lang=="sk-SK")) {
header("Location: https://www.example.sk/sk");
}
else if (($lang=="en_EN") OR ($lang=="en-EN") OR ($lang=="en_GB") OR ($lang=="en_US") OR ($lang=="en-GB") OR ($lang=="en-US")) {
header("Location: https://www.example.sk/en");
}
else {
header("Location: https://www.example.sk/en");
}
?>
I am unable to set session for $_SESSION['next'] under switch/case condition, while $_SESSION['user_id'] works perfectly before the condition. The script run into each condition of switch/case condition and redirect without setting $_SESSION['next']. Is there any specific reason why it fails to work? How to solve this?
require_once ('../src/facebook.php');
require_once ('../src/fbconfig.php');
//Facebook Authentication part
$user_id = $facebook->getUser();
if ($user_id <> '0' && $user_id <> '') {
session_start();
$_SESSION['user_id'] = $user_id;
switch((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc';{
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'def';{
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'ghi';{
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
default;{
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
}
} else {
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;
}
Your switch is all wrong. Read the manual and try this:
<?php
switch ((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc':
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'def':
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'ghi':
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
default:
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
}
You're using exit in your switch, which (unless you want your script to end at the switch) is a no-no. Instead, you have to use the break keyword.
You also use semicolons and curly braces for each case.
case 'ghi';{ ... }
NO! Proper usage is
case 'ghi':
.
.
.
break;
Update: I just noticed you use this line:
if ($user_id <> '0' && $user_id <> '') { ... }
What is <> doing in PHP code? The "standard" operator for "not equals" is != in PHP. Use it correctly or no one will want to use your code.
Second update: You never set $_SESSION['next'] in your default case. It's very likely that your switch is always going to the default case. This would cause the behavior you're experiencing.
I suggest:
if (($user_id != '0') && ($user_id != ''))
(parentheses, and the != operator)
and also a DRYer switch:
$page = array_key_exists('page', $_GET) ? $_GET['page'] : '';
switch ($page) {
case 'abc':
$next = 'AAA';
$loc = 'https://www.example.com/xxx/';
break;
case 'def':
$next = 'BBB';
$loc = 'https://www.example.com/yyy/';
break;
... // and so on
}
if (isset($next)) {
$_SESSION['next'] = $next;
// If it does not work, you have problems with your session ID, maybe?
}
// I find this syntax easier
print <<<SCRIPT
<script type="text/javascript">
top.location.href = '$loc';
</script>
SCRIPT;
exit();