Am I not using the _GET function properly to open another page? - php

I'm asking this because my teacher was displeased with how it worked. By that I mean ,when I typed in the query string to change sites, instead of typing ?page=flight and it staying that way it changed to../flight-details.php which is the direct page name.
Router.php:
<?php
$nav =array("home"=>"home.php",
"flight"=>"flight-detail.php",
"order"=>"order-flight.php",
"testimonial"=>"add-testimonial.php");
if ( isset ($_GET) )
{
header('Location: ' . $nav[$_GET['page']]);
}
else
{
header('Location:index.php');
}

There are few issues with your code, such as:
$_GET is a superglobal array, right now you are just checking whether the array is set or not. Your if condition should be like this:
if(isset($_GET['page']) && in_array($_GET['page'], array_keys($nav))){ ...
Otherwise you would get undefined index error if someone types anything other than the following four combinations, ?page=home&..., ?page=flight&..., ?page=order&... and ?page=testimonial&....
header(...); is not enough to redirect the user to a different page, use exit(); immediately after header(...); statement.
So your code should be like this:
$nav =array("home"=>"home.php",
"flight"=>"flight-detail.php",
"order"=>"order-flight.php",
"testimonial"=>"add-testimonial.php");
if(isset($_GET['page']) && in_array($_GET['page'], array_keys($nav))){
header('Location: ' . $nav[$_GET['page']]);
}else{
header('Location:index.php');
}
exit();
Here's the relevant reference:
http://php.net/manual/en/function.array-keys.php

Related

Admin only access to page, if statment doesn't work

I'm trying to give access to admin tools only to the admin.
What I tried to do: the session variable id, which is unique for every user.
first I checked if there is even a session, if there isn't I send the user to the index, than I check for the unique if of the admin "20" if the user's id is different than 20 I send him the the index.
my problem: my if statment doesn't work, I get sent back to index even when i'm logged-in as the admin.
My code:
<?php
if(isset($_SESSION['userId'])){
header('Location:index.php?b');
}
if($_SESSION['userId'] != 20){
header('Location:index.php?a');
}
?>
?a and ?b are for debugging, I get sent to index.php?a when I try to access the my page.
when I echo $_SESSION['userId'] I get 20, so maybe something is wrong with the type?(although I checked and it says that != shouldn't be effected by different types)
EDIT: sorry, I didn't describe what I wanted correctly, if the id of the user is 20 I want him to stay in the page, if it isn't I want to redirect him to index.
thanks!
Because you perform one test when that test passes or fails the comparison is over. You should probably perform a comparison like this because you only want to redirect when the ID is not 20:
<?php
session_start();
if(isset($_SESSION['userId']) && $_SESSION['userId'] != 20) {
header("Location: index.php");
exit();
}
?>
Check if session is set and if so assign its value to a variable with the null coalesce operator. Redirect using the ternary operator.
<?php
session_start()
//$_SESSION['userId'] = 19; // Redirects to index.php?a
$_SESSION['userId'] = 20; // Redirects to index.php?b
// use the null coalesce operator and ternary
$id = $_SESSION['userId'] ?? null;
($id == '20') ? '' : Redirect('index.php?a');
echo 'Still in page ...';
// Ensure an exit() after redirect
function Redirect($url) {
header('Location: ' . $url);
exit();
}
//Output: Still in page ...
?>
EDIT:
You can combine these steps to achieve this in one line:
(($_SESSION['userId'] ?? null) == 20) ? '' : header('Location: index.php?a');
This returns $_SESSION['userId'] if it's set and not null, otherwise it returns null. Then it checks this against the value 20 and uses it in the ternary operator to either do nothing ('') or redirect to index.php.
Your first if condition checks if the session is set (which is true) so it redirects you to index. So you should do:
session_start()
if(isset($_SESSION['userId'])){
if($_SESSION['userId'] != 20){
header('Location:index.php?a');
}else{
header('Location:index.php?b');
}
}

restrict page without variable , only open if coming from a page or site

page-one.php code
<?php
//page-one.php
session_start();
$_SESSION['page_one'] = time();
?>
hello this is page 1 go to page 2
Page 2
page-two.php code
<?php
//page-two.php
session_start();
//Check to see if session variable exists.
if(!isset($_SESSION['page_one'])){
//Does not exist. Redirect user back to page-one.php
header('Location: 404.php');
exit;
} ?>
this is page 2
Works perfect but I have 2 questions:
what if i delete page-one bcz i want to show page 2 to all vistors who are coming on page 2 by clicking a link
or what if user is coming on page-two through google.com , in this case how page-two will pass page_one variable
This doesn't make much sense, but for your specific questions:
if(!isset($_SESSION['page_one']) &&
strpos($_SERVER['HTTP_REFERER'], 'google') === false &&
strpos($_SERVER['HTTP_X_FORWARDED_FOR'], 'google') === false &&
file_exists('page-one.php')
{
header('Location: 404.php');
exit;
}
Check if the session variable is not set
Check if HTTP_REFERER is not google
Check if HTTP_X_FORWARDED_FOR is not google
Check if page-one.php has not been deleted
$_SERVER['HTTP_REFERER'] is not reliable as it may be wrong, a proxy server or empty and $_SERVER['HTTP_X_FORWARDED_FOR'] is not guaranteed to be set or reliable.
With the previous caveats in mind, you can see if someone came from another site by checking:
if(!isset($_SESSION['page_one'] &&
!isset($_SERVER['HTTP_REFERER'] &&
!isset($_SERVER['HTTP_X_FORWARDED_FOR'])
{
header('Location: 404.php');
exit;
}
If you add a get parameter to all links then it's easier:
Page 2
Then:
if(!isset($_SESSION['page_one'] && !isset($_GET['link'))
{
header('Location: 404.php');
exit;
}

Using || in if statements

If a user visits test.php?number=1 or test.php?letter=1, I want them to stay on the page. If they visit test.php, I want them to be re-directed.
I have tried to accomplish the above using the script below, however the following happens:
if the user visits test.php?number=1, they stay on the page.
If the user visits test.php?letter=1, they are re-directed.
if(!isset($_GET['number']) === false || $_GET['letter'] === false) {
echo '<h1>Hello</h1>';
}else{
header('Location: redirect.php');
exit();
}
Note: the value of number and letter can change! It won't always be 1!
Instead of isset() use empty() in this case as an non-existent value does not do you any good, ie. test.php?number= with no value entered for number. Ditto for letter.
The following will check if either number or letter contain a value, to which the condition will satisfy and <h1>Hello</h1> will print. Otherwise, if neither contain a value, you will be redirected.
if ( ! empty($_GET['number']) || ! empty($_GET['letter']) ) {
echo '<h1>Hello</h1>';
}
else {
header('Location: redirect.php');
exit;
}

else if - what am I doing wrong?

I have the following code which I use in conjunction with a members script which displays a members username the page or asks guests to login or register.
PHP code:
if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
echo "Welcome Guest!<br><small>Login or Register</small>";
It works perfectly well, though now I want to modify it so if a user with admin privileges logs in it identifies the username and offers a link to the admin page.
So here's my modified code:
<? php
$validateadmin = $_SESSION['username'];
if ($validateadmin == "admin1" or $validateadmin == "admin2")
{
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}
else if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>
Any idea's what I'm doing wrong? It either leaves me with a blank page or errors.
I know it's probably a newbie error but for the life of me I don't know what's wrong.
Generally you should use elseif in php not "else if" because the php parser will interpret else if as else { if { .... }} and you can have some weird errors.
Also, it is a great practice to ALWAYS use braces with control statements to avoid dangling clauses.
Also to avoid notices about array indexes don't do checks like if($array[$index]) if the index may not exist. Use any of array_key_exists, isset, empty, etc (they all are slightly different) to check if an array contains a key you are looking for.
try the following
<?php #removed space
session_start(); #you will need this on all pages otherwise remove it if already called
$validateadmin = $_SESSION['username'];
if($validateadmin == "admin1" || $validateadmin == "admin2"){
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}elseif(isset($_SESSION['username'])){ #you should use isset to make sure some variable is set
echo $_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}else{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>

Help with PHP if / else statement

On my site, forms are brought in via AJAX and checked against a sessionid. I know this is not optimal, but it's working for us. If the referrer doesn't have the session ID they are redirected back to "anotherpage". I need to allow some outside URL's access the form directly.
we set the sessionid on the page with the link to the form.
Here is what we have now on the form page:
<?php
$code = $_GET['sessionid'];
if(strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>
I need to allow some outside domains direct access to the form page and am having issues with this:
(I'm putting it above the head tag on the form page)
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if(strcmp( $code , 'XXXXX' ) !=0) {
header("Location: http://www.domain.com/anotherpage.php");
} else {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
}
}
?>
this still bounces me back to "anotherpage.php" any ideas?
********EDIT*******
thx for the help, it works ad I requested. Now I see what I asked wasn't entirely correct. This appends the URL with =sessionid?=XXXXX. This isn't an issue on my site because I'm loading the content with .jquery .load so the URL doesn't change. I don't want the sessionid to be visible, and now it is. Can I either a) "trim" the url somehow or b) separate the two functions so they are exclusive?
if(strcmp( $code , 'XXXXX' ) !=0) {
if (preg_match("/site1.com/",$referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else {
header("Location: http://www.domain.com/anotherpage.php");
}
}
As I read your post, you want anyone from the preg_match to get the desired page regardless of sessionID status, so you don't want to test sessionID first.
Start the if block with the preg_match test.
Your first if is checking to see if they don't have the $code and redirecting them. This will always be the case. You should probably check the $referrer first and then do the $code check.
Try reverse if with else
<?php
$code = $_GET['sessionid'];
$referrer = $_SERVER['HTTP_REFERER'];
if (preg_match("/site1.com/", $referrer)) {
header('Location: http://www.domain.com/desiredpage.php');
} else if (strcmp( $code , 'XXXXX' ) != 0) {
header("Location: http://www.domain.com/anotherpage.php");
}
?>
If I'm not misunderstanding this, the problem is in the order in which you are checking things.
If you want to allow some referrers to access the site even if they don't have the session id, you have to check for that before checking for the session id. Otherwise, they will end up being treated just like everyone else.
You can either switch the order of the conditions (first check for the referrer and then check fo the session id) or check for the referrer inside the branch in which you already know the session id is not valid.
The issue could be in your regex, it should be:
if (preg_match("/site1\.com/",$referrer))
notice escaping the dot (.)

Categories