Search code examples
phpgetisset

!isset($_GET["sample"]) is not working as expected


I'm having trouble getting an !isset test working properly. I tried a few different things but can't get it working as I expected.

Here is the scenario: if the get variable isn't set (i.e. someone visits the page directly and not to the page with the get variables in the url) then send them to another page.

This is what I tried:

if(!isset($_GET["e"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
if(!isset($_GET["k"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}

I also tried this:

if(isset($_GET["e"])){}else{$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}
if(isset($_GET["k"])){}else{$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}

I know my variables are fine because if I echo the gets or assign them to variables, I get no problems:

$currentEmail = htmlspecialchars($_GET["e"]);
$currentKey = htmlspecialchars($_GET["k"]);

echo($_GET["e"]);
echo("</br>");
echo($_GET["k"]);

I also heard that by doing the check below, you can find out if someone came to the page by clicking a link. i.e. adding "a" instead of an actual get variable name. Does anyone know if that's true?

if(!isset($_GET["a"])){$goToPage = 'Location: http://'.$_SERVER['SERVER_NAME'].'/';header($goToPage);}

Solution

  • The code you provided works absolutely fine and as expected on my system (Apache 2.2 on Debian).

    You may need to check whether your Location: header is actually being sent. I'm guessing you're sending some output before your header() call, which will mean your header won't be sent at all - your header must be the absolute first output, which means you can't even have a blank line before your <?php tag. Depending on your error reporting settings, you may not see a warning when this happens. Take a look at PHP header redirect not working.