Preventing PHP to show notices for undefined arguments when using exceptions

StackOverflow https://stackoverflow.com/questions/20829399

  •  22-09-2022
  •  | 
  •  

Domanda

I think the question is fairly self-explainatory, here's the code:

HTTP Request: localhost/execute.php?password=testing&command=create&api=api

This is part of the execution code.

try 
{
    $TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
}
catch(Exception $createError)
{
    echo $createError->getMessage();
}

Here's the class method:

function createUser($email, $cellphone, $areaCode = 1)
{   
    if(!isset($email))
        throw new BadMethodCallException('(CTFA_SAMP->createUser) email ('. $email .') is missing.');
        
    if(!isset($cellphone))
        throw new BadMethodCallException('(CTFA_SAMP->createUser) cellphone ('. $cellphone .') is missing.');

    $authyLibrary = new Authy_Api($this->API, $this->connectionURL);
    $requestResult = $authyLibrary->registerUser($email, $cellphone, strval($areaCode));
    
    if($requestResult->ok())
    {
        echo $requestResult->id();
    }
    else
    {
        foreach($requestResult->errors() as $field => $message) 
            echo "$field = $message";
    }
}   

The PHP pages prints:

Notice: Undefined index: email in D:\xampp\htdocs\tfasamp\execute.php on line 46

Notice: Undefined index: cellphone in D:\xampp\htdocs\tfasamp\execute.php on line 46

Notice: Undefined index: area_code in D:\xampp\htdocs\tfasamp\execute.php on line 46

(CTFA_SAMP->createUser) email () is missing.

How do I prevent PHP from giving me those notices as I am using exceptions to show them?

È stato utile?

Soluzione

$TFA_SAMP->createUser($_GET['email'], $_GET['cellphone'], $_GET['area_code']);
                      ^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^

The non-existing variables are accessed here. Nobody cares that you're later checking for isset on completely different variables and are throwing exceptions, the problem is in the above line. You need to fix it there. For example:

$args = $_GET + array('email' => null, 'cellphone' => null, 'area_code' => null);
$TFA_SAMP->createUser($args['email'], $args['cellphone'], $args['area_code']);

Alternatively, use isset statements here and throw exceptions for missing user input.

Basically, the code which touches $_GET deals with completely unpredictable user input. That's your first line of defence in which you need to check for existing or non-existing values. You can't roll this as responsibility into code which comes later.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top