3

I am testing for a given post request field on a script that can be called either from the command line, or over HTTP as a GET or POST request. As such, $_POST can be undefined. Is there a simple way of rewriting this statement?

if (isset($_POST) && isset($_POST['function']) && $_POST['function'] == "login"):

I could suppress errors with the @-operator — is that bad practice?

if (@$_POST['function'] == "login"):

I could use PHP 7.0's null coalesce operator, but that introduces a useless literal purely designed to throw a false:

if (($_POST['function'] ?? null) == "login"):
DanMan
  • 11,323
  • 4
  • 40
  • 61
Charlie Harding
  • 653
  • 8
  • 22
  • 1
    Probably not too popular of an opinion, but I think this is one case where using error suppression is justified. Implications when that index doesn't exist are obvious. – Daniel Sloof Dec 23 '15 at 16:19
  • Variations of this question get asked now and then. I always recommend to stop caring, write a custom wrapper function and just use `if (get_input('function') == 'login')`. – Álvaro González Dec 23 '15 at 16:23
  • @DanielSloof No need just use `php_sapi_name()` – RiggsFolly Dec 23 '15 at 16:38
  • @RiggsFolly but that introduces another test for the `if` statement. Also, you have marked this as duplicate: can you provide a link to where this has been asked before? – Charlie Harding Dec 23 '15 at 17:49
  • The link is at the top of your question in the yellow box – RiggsFolly Dec 23 '15 at 18:09
  • _but that introduces another test for the if statement_ Yes but one that provides an easy way of deciding where the script is running. – RiggsFolly Dec 23 '15 at 18:34
  • 2
    @RiggsFolly this is not a duplicate of "What is the canonical way to determine commandline vs. http execution of a PHP script?" – Andrea Dec 24 '15 at 22:07

1 Answers1

2

If it helps, you don't need both isset() tests:

if (isset($_POST['function']) && $_POST['function'] == "login"):

Will work properly if $_POST is not set. For example:

php > var_dump(isset($notset[123][456]));
bool(false)
php >

I would also consider your usage of the null-coalesce operator to be proper and clean.

if (($_POST['function'] ?? null) == "login"):

This looks great to me.

You could also abstract this logic away behind some type of wrapper function:

function getFunction()
{
    return ($_POST['function'] ?? null);
}

Or, for older PHP:

function getFunction()
{
    return isset($_POST['function']) ? $_POST['function'] : null);
}
Will
  • 24,082
  • 14
  • 97
  • 108