1

I am checking if a variable 'auth' is set on either _POST or _GET and want two different actions. I have managed to get it working with if / else but it looks ugly and wasteful?

If POST isn't set, check GET. If GET is set, do nothing <- that part doesn't look right?

if ( !isset( $_POST[ 'auth' ] ) ) 
{
  if (isset( $_GET[ 'auth' ] ) ) {
    //do nothing

  } else {
    //redirect
    header( 'Location: https://google.com' );
    exit();
  }
}

Is there a whole new approach here? Like check both, if neither are set go to redirect, if ONE is set continue with page?

if(isset($_GET['auth']) xor (isset($_POST['auth']))) {
    //do nothing
}else{
 //redirect
 header('Location: https://google.com');
 exit();
}

^ if these are acceptable statements, what should be in the 'do nothing' section?

Jonno
  • 1,542
  • 3
  • 22
  • 39

2 Answers2

2

You can do it simply like using && :

if(!isset($_GET['auth']) && !isset($_POST['auth'])) {
  header('Location: https://google.com');
  exit();
}
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • 1
    Could potentially be reduced to just `!isset($_REQUEST['auth'])`. – El_Vanja Feb 25 '21 at 12:19
  • 1
    @El_Vanja yes it can be, but it has own draw bags (As it includes cookie as well) : [What's wrong with using $_REQUEST?](https://stackoverflow.com/a/2143042/4248328) – Alive to die - Anant Feb 25 '21 at 12:25
  • 1
    Yes, but that's true only of outdated versions. From the docs: `Note that the default distribution php.ini files does not contain the 'C' for cookies, due to security concerns.`; either way - that's why I've said "potentially". It depends on the environment. – El_Vanja Feb 25 '21 at 12:39
  • @El_Vanja agreed on that. – Alive to die - Anant Feb 25 '21 at 12:40
2

You could use the null coalesce (??) to chain the various values and default to null of nothing found, then check for null...

$auth = $_POST[ 'auth' ] ?? $_GET[ 'auth' ] ?? null;
if ( $auth == null )
{
    //redirect
    header( 'Location: https://google.com' );
    exit();
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55