I have
$CID = $_REQUEST ['cid'];
$UID = $_REQUEST ['uid'];
if ($UID == '0') {
header ( 'Location: url/you-need-to-log-in-before-redirect/' );
} else {
switch ($CID) {
// go to URL1 case number is the same as CID
case "147" :
header ( 'Location: url' . $UID );
break;
case "148" :
header ( 'Location: url' . $UID );
break;
default :
echo "Something went terribly wrong";
}
}
Is this ok? I have a problem of $UID registering as blank which should not be possible as it is always set to be 0 for non-registered users and for registered it's unique. should i use exit() instead of break? or both? Or should i not be using header loaction at all to send users forward...i have hundreds of cases inside this switch case statement. i cant post any actual urls so the 'url' in example is not a variable but just a placeholder for the actuall full address.
Is the zero's type integer? If yes your condition is wrong, because it tests for string but you have an integer.
Try: if ($UID == 0) { and the same for the switch cases.
Related
I make some function in php, but I am getting stuck
if (isset($_GET['page']) )
{
$open = __DIR__.'/../view/html/'.$_GET['page'].'.php';
if (file_exists($open)){
include $open; //<<<<can i//
}
else {
"echo "The file not found";
}
}
If true, I want to include that file in another place, but how?
I am trying to put the code in where I want, but the __DIR__ is not working as I expected. I don't know how to fix it to become right. Solution cannot be found in the tutorial.
I would use:
if( isset( $_GET['page'] ) ) {
switch( strtolower( $_GET['page') ) ) {
case 'download':
include '../download.php';
break;
case 'blog':
include '../blog.php';
break;
// ... And so on
default:
echo 'File not found';
}
} else {
echo 'No file specified';
}
This way you have full control over which files can be included!
You have to do like this.
Use file_get_contents()
if (file_exists($open)){
file_get_contents($open);
}
The answer to your question is yes, that will work. Whether or not you should use readfile(), file_get_contents() or include depends on the contents of the file. If you have php code in that file, you need either include or require. But this actually brings up another problem.
As mentioned in the comments by #anonymous, you are exposing yourself to an LFI attack. To resolve this, pages should be defined as a whitelisted array. You should then check if the page is in the whitelisted array. If it is not, do not attempt to open that file.
$pages = array(
'page1',
'page2'
);
Then you can make a reference and check if it exists.
if(in_array($_GET['page'], $pages)){
//now check for the file
$open = __DIR__.'/../view/html/'.$_GET['page'].'.php';
if(file_exists($open)){
include $open;
}
} else {
//page does not exist, redirect them elsewhere.
header('Location: http://example.com/404.php');
}
I've put together a small script in PHP that checks for the browser's language settings and redirect them to a language version of the site (WP multisite),
function redirect() {
$language = substr( $_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2 );
switch( $language ) {
case 'sv':
header( 'Location: http://www.example.com/sv/' );
break;
case 'no':
header( 'Location: http://www.example.com/no/' );
break;
case 'da':
header( 'Location: http://www.example.com/da/' );
break;
default:
header( 'Location: http://www.example.com/' );
break;
}
}
if ( strlen($url) < 4 ) {
session_start();
if ( empty($_SESSION[ 'language' ]) ) {
$_SESSION[ 'language' ] = true;
redirect();
}
}
When testing with Mobile Safari or Mobile Chrome the redirect doesn't appear to work. Is there any special output for the accept language for mobile browsers that I need to consider?
Update: After some more debugging I found out this:
Mobile Safari displays the correct language when echoing HTTP_ACCEPT_LANGUAGE but does not redirect.
Mobile Chrome (iOS only, works on Android) doesn't display the correct language (defaults to "en").
iOS parses the http header data in a different order, compare iOS Chrome (en-US,en;q=0.8,sv;q=0.6) and OSX Chrome (sv,en-US;q=0.8,en;q=0.6).
Try this and let us know the output please
function redirect() {
$language = substr( $_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2 );
switch( $language ) {
case 'sv':
header( 'Location: http://www.example.com/sv/' );
break;
case 'no':
header( 'Location: http://www.example.com/no/' );
break;
case 'da':
header( 'Location: http://www.example.com/da/' );
break;
default:
die('Default location');
/* if you get this message on mobile devices, then this line
$language = substr( $_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2 );
is faulty. Perhaps as #chris85 mentioned, HTTP_ACCEPT_LANGUAGE is
not populated so mobile behaves as a default by not redirecting to
other languages. If this is the case, fix that line
and remove the die();*/
header( 'Location: http://www.example.com/' );
break;
}
die(); // leave this one in. It forces the server to flush data to the browser
}
UPDATE to my previous answer
The HTTP_ACCEPT_LANGUAGE is set via headers and will give different values for everyone.
In my case I am in south america on an computer setup in english so my lang headers have english and spanish
settings with a bias towards english.
session_start();
function redirectToLang($langCode){
// use if's instead of switch so that you can
// check exact matches and presence of a substring
if ($langCode == 'sv'){
$langPath = 'sv';
}else if (strpos($langCode, 'en') !== false){ // this would match en, en-CA, en-US
$langPath = 'en';
}else if ($langCode == 'no'){
$langPath = 'no';
}else{
$langPath = 'en';
}
// you should have no output from the server before this line!
// that is no echoes, print_r, var_dumps, headers, etc
header( 'Location: http://www.example.com/' . $langPath .'/' );
die();
}
function parseLang(){
// echo $_SERVER['HTTP_ACCEPT_LANGUAGE']; in my case
// Chrome Mac OS: en,es;q=0.8
// Chrome Android 5.1: en-US;en;q=0.8,es;q=0.6
// IE Windows Phone 8.1: en-US,en;q=0.5
// Safari iOS: en-US
// Chrome iOS: en-US,en;q=0.8
// get the lang and set a default
$lang = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en';
// parse the lang code. This can be as simple or as complex as you want
// Simple
$langCode = substr($lang, 0, 2); // in my case 'en'
// Semi Complex (credits to http://www.thefutureoftheweb.com/blog/use-accept-language-header)
$languages = array();
preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $lang, $parsed);
if (count($parsed[1])) {
$languages = array_combine($parsed[1], $parsed[4]);
foreach ($languages as $lang => $val) {
if ($val === '') $languages[$lang] = 1;
}
arsort($languages, SORT_NUMERIC);
}
// var_dump($languages); in my case
// array (size=2)
// 'en' => int 1
// 'es' => string '0.8'
$langCode = key($languages); // in my case 'en'
return $langCode;
}
if (!isset($_SESSION['lang'])){
$langCode = parseLang();
$_SESSION['lang'] = $langCode;
redirectToLang($langCode);
}else{
// we already know the language and it is in $_SESSION
// no need to parseLang nor redirect
}
In my case, all devices redirect correctly. My guess is that there is something happening on the logic that calls redirect()
// this part
if ( strlen($url) < 4 ) {
session_start();
if ( empty($_SESSION[ 'language' ]) ) {
$_SESSION[ 'language' ] = true;
redirect();
}
}
and the session var
is bypassing the redirect logic. Try the code above and clear all cookies and sessions from all devices so that the $_SESSION['language'] var you have
set during testing wont mess up the results. Let us know what happens on your end.
I'm quoting..
"A more contemporary method would be to use http_negotiate_language():"
Did you check this one?
Using the PHP HTTP_ACCEPT_LANGUAGE server variable
This works fine on my desktop browsers, and mobile devices. I too was experiencing session problems on devices only and most often, I was relying on a session variable being empty to fulfill the requirements of my condition when in fact the variable was still in existence, or there simply was no session_id() instantiated.
?reset will clear the session.
It also will run the redirect if the language has changed.
<?php
session_start();
if (isset($_REQUEST['reset'])) {
unset($_SESSION);
$_SESSION['PREVIOUS_SESSION'] = '&cleared=1';
}
function redirect($loc) {
$_SESSION[ 'language' ] = true;
$_SESSION['last_language'] = $language;
header( 'Location: ?r='.$loc.$_SESSION['PREVIOUS_SESSION']);
}
$language = substr( $_SERVER["HTTP_ACCEPT_LANGUAGE"],0,2 );
if (( empty($_SESSION[ 'language' ]) ) || ($_SESSION['last_language'] != $language)) {
redirect($language);
}
echo '<pre>';
print_r($_SESSION);
echo '</pre>';
if (!empty($_SESSION['PREVIOUS_SESSION'])) {
unset($_SESSION['PREVIOUS_SESSION']);
}
?>
You should really give us examples of what is the value of $_SERVER["HTTP_ACCEPT_LANGUAGE"] for the three cases.
Anyway, please note that according to the RFC2616 of HTTP/1.1, the choice of a language is much more complicated than just taking the two first chars of the header.
Each language-range MAY be given an associated quality value which
represents an estimate of the user's preference for the languages
specified by that range. The quality value defaults to "q=1". For
example,
Accept-Language: da, en-gb;q=0.8, en;q=0.7
would mean: "I prefer Danish, but will accept British English and
other types of English."
Nothing says that those headers are sorted, nor that the preffered language of the user is the first one in the list. And the language configuration could also not be configured in the browser or OS.
Ideally, to select the best language, you have to parse this header this way:
Split the string on commas
Split every substring found on the semicolon character
When a numeric value is not given, use the default value of 1.0
Sort the result using this numeric value
Compare this list to the list of languages that are available on your website and find the best one.
You really shouldn't rely on getting first two characters. You really need to rely on inspecting the whole string and understanding what the best language selection should be. Those string values have specific meaning, and for example in one of your cases of the "problem" strings, you would actually be doing most appropriate behavior to show en instead of sv. You can obviously write logic to break apart the accept language, investigate the constituent parts, and take appropriate action, but you also might consider using something like:
http_negotiate_language
to do this for you. There are probably dozens of other scripts available from quick google search to really work with this header in a more appropriate fashion than just looking at the two first characters.
Also, you can check out similar question here: Using the PHP HTTP_ACCEPT_LANGUAGE server variable
I'm trying to make redirect if the user is not signed in.
so it should read like this:
If FName is unset and $page does not equal 'new host' or 'login'
then set header to login and set error message.
All the parts work on their own, but not when I try to assemble them.
Edit, I have it working with a switch now but I'm still intrigued on why this if didn't work.
The || means true if either condition is true.
The and checks to see if the leading and following conditions are true.
Should I be using && or does that make a difference?
Here is my code:
if ( !isset($_SESSION['FName']) and
( $page == '/e-Party/Login/Login.php' || $page == '/e-Party/NewHost/NewHost.php')){
echo "not logged in";
$_SESSION['Error'] =
"you must login to use our site,<br>. Or create a account if you don't have one";
header( 'Location: /e-Party/Login/Login.php' );
exit();
}
Edit, here is my working switch.
if ( !isset($_SESSION['FName']))
switch ($page) {
case '/e-Party/NewHost/NewHost.php':
break;
case '/e-Party/Login/Login.php':
break;
default:
$_SESSION['Error'] =
"you must login to use our site,<br>. Or creat a account if you dont have one";
header('Location: /e-Party/Login/Login.php');
exit();
}
A comment helps much more than a down vote, thank you for reading.
Your if and switch are not equivalent: the switch version would be equivalent to
if (!isset($_SESSION['FName']) && $page != '/e-Party/Login/Login.php' && $page != '/e-Party/NewHost/NewHost.php') {
...
}
I changed the if to a switch and it works perfectly as I intended.
if ( !isset($_SESSION['FName']))
switch ($page) {
case '/e-Party/NewHost/NewHost.php':
break;
case '/e-Party/Login/Login.php':
break;
default:
$_SESSION['Error'] =
"you must login to use our site,<br>. Or creat a account if you dont have one";
header('Location: /e-Party/Login/Login.php');
exit();
}
You wrote
If FName is unset and $page does not equal 'new host' or 'login' ...
But you wrote (in PHP)
if !isset($_SESSION['FName']) and
($page == '/e-Party/Login/Login.php' || $page == '/e-Party/NewHost/NewHost.php')
That is, page equals A or page equals B. To make PHP match English:
if !isset($_SESSION['FName']) and
($page != '/e-Party/Login/Login.php' || $page != '/e-Party/NewHost/NewHost.php')
which is flawed. It is equivalent to
if !isset($_SESSION['FName'])
I've been studying PHP using only the internet, so I've been experiencing errors.
<?php
$name = $_POST['name'];
$lg = $_POST['lg'];
if (is_string($name) && is_numeric($lg)) {
header( "Location: portal.php?ejhbusbhdubr=nennuncuiecbdhbcvhebchebcdjebcdsjhbcebhfcvebhdchebhcvhervbhecbvecveh" ) ;
}
if (empty($name) && is_numeric($lg)) {
echo "Please enter your name.";
}
else {
header ("Location: index.php?invalid=true");
}
?>
I'm having problems with the second if statement. What I'm trying to do is that I'm trying to make an error message appear when the $name variable is left empty, and the $lg variable isn't. I think the is_string variable handler's the problem here. Perhaps a string can be empty. But as I said, since I don't have a book, I don't know what to change it too.
In case you still don't get what I mean,
Name: ""
LG: "1234"
I want the above to return as error. Help would be appreciated.
Try to write you condition like this:
if (empty($name) && !empty($lg))
Try it like this, I just moved your if over the first one, and changed it a bit. You have to test if the string is empty before testing, if it is a string. I mean is_string will return true even if the string is empty.
<?php
$name = $_POST['name'];
$lg = $_POST['lg'];
if (empty(trim($name)) && is_numeric($lg)) {
echo "Please enter your name.";
}
elseif(is_numeric($lg)) {
header( "Location: portal.php?ejhbusbhdubr=nennuncuiecbdhbcvhebchebcdjebcdsjhbcebhfcvebhdchebhcvhervbhecbvecveh" ) ;
die();
}
else {
header ("Location: index.php?invalid=true");
die();
}
This question already has answers here:
Why is PHP not replacing the variable in string? [closed]
(2 answers)
Closed 8 years ago.
I have this code here:
<?php
$search=htmlspecialchars($_GET['load']);
$method = isset( $_GET['btnAction'] ) ? $_GET['btnAction'] : '';
switch( $method ) {
case 'Search':
header('Location: search.php?load=$search');
break;
case 'Im Feeling Lucky':
//do chapter two stuff
header('Location: search_lucky.php?load=$search');
break;
default:
echo 'Not a valid operation';
}
?>
Everything works except the $search variable, I don't understand what is wrong.
Can someone tell me why $search variable dont work when i hit this url: handler.php?load=keyword&btnAction=Search
The problem is in your header() function.
header('Location: search_lucky.php?load=$search');
should be
header("Location: search_lucky.php?load=$search");
as php treats everything between the (') as literals. so it's literally passing load=$search
Have you tried using an if() statement to do it.. see below..
<?php
$search=htmlspecialchars($_GET['load']);
if(isset($_GET['btnAction']) {
$method = $_GET['btnAction'];
}
switch( $method ) {
case 'Search':
header('Location: search.php?load=$search');
break;
case 'Im Feeling Lucky':
//do chapter two stuff
header('Location: search_lucky.php?load=$search');
break;
default:
echo 'Not a valid operation';
}
?>
EDIT: just noticed the the 'Search' with capitol S. Change to lowercase might work better.
This code is a little bit broken, so take a look at this after it's changed:
<?php
$search=htmlspecialchars($_GET['load']);
$method = isset( $_GET['btnAction'] ) ? $_GET['btnAction'] : '';
switch( $method ) {
case "search":
header("Location: search.php?load=$search");
break;
case "Im Feeling Lucky":
//do chapter two stuff
header("Location: search_lucky.php?load=$search");
break;
default:
echo 'Not a valid operation';
}
?>
The reason is because you were testing $method (which had a value of 'search') to see if it matched 'Search' (with a capital S). Those two cases do not match, which is why you were seeing "Not a valid operation" output.
In PHP, variables are interpreted only in double quotes.
header("Location: search.php?load=$search");
To use single quote you'll need to concatenate the values
header('Location: search.php?load='.$search);