Okay, I got this code build up but i guess it is somehow ugly.
Can this been done better?
if (isset($_GET['lang'])) {
$lang = $_GET['lang'];
if ($lang == 'en') {
$_GET['method']($lang);
}
elseif ($lang == 'nl') {
$_GET['method']($lang);
}
else {
$_GET['method']($lang);
}
}
else {
$lang = '';
$_GET['method']($lang);
}
function GET($name, $default=null)
{
if ( !isset($_GET[$name]) )
return $default;
return $_GET[$name];
}
$method = GET('method'); // Don't forget to error-check $method too, or it will be a major security hole!
$method(GET('lang',''));
It appears that you intend to $_GET['method']($lang) no matter what the value of $lang is. So don't check the value; just determine it, and then use it.
if (isset($_GET['lang'])) { $lang = $_GET['lang']; }
else { $lang = ''; }
$_GET['method']($lang);
Won't
if (isset($_GET['lang'])){
$lang = $_GET['lang'];
if ($lang == 'en'){
$_GET['method']($lang);
} elseif ($lang == 'nl'){
$_GET['method']($lang);
} else {
$_GET['method']($lang);
}
} else {
$lang = '';
$_GET['method']($lang);
}
do exactly the same as
if (isset($_GET['lang'])){
$lang = $_GET['lang'];
$_GET["method"]($lang);
} else {
$lang = '';
$_GET['method']($lang);
}
#Highmastdon: To make the example complete see my correction
Since you're calling $_GET['method']($lang); in every case, including the else, you don't need all those conditions to do the same thing; the code you've given could be written as simple as this:
$lang = isset($_GET['lang']) ? $_GET['lang'] : '';
$_GET['method']($lang);
You could even combine those two lines into one like so:
$_GET['method'](isset($_GET['lang']) ? $_GET['lang'] : '');
...although that is starting to get a bit un-readable.
However, I would echo the point made by #Vilx- that calling a function name that is specified directly from the browser can be a major security risk, so you*really* need to vet the contents of method and lang. (imagine if the url looked like ?method=eval&lang=rm+index.php)
$_GET['method'](isset($_GET['lang']) ? $_GET['lang'] : '');
But please, please please don't do this. You have a massive security hole, if the user specifies method=eval (or any other function that you don't really want called).
Related
I try to make a 'change languge system' for my script. I already created my class and everything works fine. My problem is next: if I have URL index.php?lang=fr , my website language is changed as long I have ?lang=fr. If I remove ?lang=fr from URL, language is changed too back to english. What is wrong in my conditions ?
P.S: $available_langs is an array with en, fr and ro.
if(isset($_GET['lang']) && $_GET['lang'] != ''){
if(in_array($_GET['lang'], $available_langs)){
$_SESSION['lang'] = $_GET['lang'];
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
} else {
$_SESSION['lang'] = "en";
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
}
} else {
if(isset($_SESSION['lang'])){
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
} else {
$_SESSION['lang'] = "en";
$lang = new Language("languages/");
$lang->setLang($_SESSION['lang']);
}
}
1)
I have this:
function ObtainRequest($Field, $Method) {
$Returned = "";
if ($Method == "POST")
$Returned = $_POST[$Field];
else if ($Method == "GET")
$Returned = $_GET[$Field];
else
$Returned = $_REQUEST[$Field];
return $Returned;
}
Now, using the function:
if (isset(ObtainRequest("OneField","POST"))) {
DoSomething();
} else if (!isset(ObtainRequest("OneField","POST"))) {
DoOtherthing();
}
But my script isn't running (SHOWING PLANK PAGE)...
What's my mistake?
2)
The $_REQUEST is lost inside of function?
This code works!!:
if (isset($_REQUEST["OneField"])) {
DoSomething();
}
This code doesn't work!!:
if (isset(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
This code doesn't work!!:
if (empty(ObtainRequest("OneField","REQUEST"))) {
DoSomething();
}
3)
Is it applicable to Session too?
Your mistake is here:
$Method == "Post"
But you passing uppercased POST:
ObtainRequest("OneField","POST")
Fix with strtoupper():
function ObtainRequest($Field, $Method) {
$Returned = "";
$Method = strtoupper($Method);
if ($Method == "POST")
$Returned = isset($_POST[$Field]) ? $_POST[$Field] : false;
else if ($Method == "GET")
$Returned = isset($_GET[$Field]) ? $_GET[$Field] : false;
else
$Returned = isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
return $Returned;
}
Also, this function might be shortened with switch construction:
function ObtainRequest($Field, $Method) {
switch(strtoupper($Method)){
case "POST": return isset($_POST[$Field]) ? $_POST[$Field] : false;
case "GET": return isset($_GET[$Field]) ? $_GET[$Field] : false;
default: return isset($_REQUEST[$Field]) ? $_REQUEST[$Field] : false;
}
}
Second problem is that isset() might be used with variables, but not with function results. Use boolean check instead:
if (ObtainRequest("OneField","POST") !== false) {
DoSomething();
} else if (ObtainRequest("OneField","POST") === false) {
DoOtherthing();
}
Is it applicable to Session too?
Well, if you interested in my opinion: I would not mix $_SESSION in such function with $_POST, $_GET and $_REQUEST, because $_SESSIONs meaning is different. Also, it exists differently, not like them.
However something like this function might be realized for $_SESSION itself.
The first problem which I can see that you are using post instead of POST...
yes you can do this with sessions too, but codes need to be modified a bit..
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'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.
Can anyone tell me why this doesn't work?
<?php
$lang = $_get["lang"];
if (($lang == "fr"))
{
session_destroy();
session_start();
$_SESSION['lang'] == "fr";
}
if (($lang == "en"))
{
session_destroy();
session_start();
$_SESSION['lang'] == "en";
}
if (isset($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else
{
$lang = "fr";
}
?>
I just can't seem to get it to work and I tried a lot of different things. Just need a direction to the mistake.
It's running on PHP5 on an Apache server if that's any help.
Even without the session I can't even get the $_get to work. With normally is never the case.
$_SESSION['lang'] == "fr";
two equal signs mean comparision operator.
assignment is = (one equal)
One obvious thing is
$_get["lang"];
Variables are case sensitive in PHP. It must be
$_GET["lang"];
if that doesn't solve your problem, you need to describe in detail what exactly doesn't work.
I have re-factored your code to make it easier to work with in the future. As Pekka says and I asked perhaps you need/want $_GET.
<?php
session_start();
$language = $_GET['lang'];
$allowable_languages = array(
'en',
'fr',
);
if(in_array($language, $allowable_languages)) {
$_SESSION['lang'] = $language;
} else {
$_SESSION['lang'] = 'fr';
}
?>
Updated: In answer to your comment:
<?php
session_start();
if(isset($_GET['lang'])) {
$language = $_GET['lang'];
$allowable_languages = array(
'en',
'fr',
);
if(in_array($language, $allowable_languages)) {
$_SESSION['lang'] = $language;
}
}
if(!isset($_SESSION['lang'])) {
$_SESSION['lang'] = 'fr';
}
?>
U just made a single mistake i.e, u are using wrong syntax it should be $_GET['lang'];
Your code doesn't work because session_start() can't be used directly after session_destroy(). Btw, you don't need to destroy session. Just redefine your variable:
$lang = 'fr';
if(isset($_GET['lang']) && in_array($_GET['lang'], array('fr', 'en'))) $lang = $_GET['lang'];
$_SESSION['lang'] = $lang;
For those who thinks the problem is lower case variable - PHP variables are case insensitive.
You are both right. There was a lot of different error. Both the "=" and "==" problem plus the $_GET case sensitive problem.
Here the code i god to work both the $_GET plus the session.
Thanks a lot. I've spend all night trying to find those error plus think i got errorblind.
<?php
$lang = $_GET["lang"];
if (($lang == "fr"))
{
session_destroy();
session_start();
$_SESSION['lang'] = "fr";
}
if (($lang == "en"))
{
session_destroy();
session_start();
$_SESSION['lang'] = "en";
}
if (isset($_SESSION['lang']))
{
$lang = $_SESSION['lang'];
}
else {
$lang = "fr";
}
?>