vendredi 15 mai 2020

Should I use multiple conditions for an if clause when I know one condition depends on the other?

I know this question touches the limits of uselessness, but please consider the fact that it's a real doubt that I faced in other similar cases, and that I did research on the topic before asking.

Scenario:

I am developing a WordPress plugin in PHP, and I am using nonces to avoid CSFR attacks.

Until now, I just used to check if the form is submitted before taking action on the potential submitted data.

But now, I also want to verify the used nonce token.

For that purpose, WordPress offers the wp_verify_nonce($nonce) function.

In many examples I see that the verification is done as follows:

if(isset( $_POST['nonce'] ) && wp_verify_nonce( $_POST['nonce'], ... )){
...
}

But I have a question, since the second condition clearly depends on the first one.

Question:

Would it be more correct to put one condition inside the other, as follows?

if(isset( $_POST['nonce'] )){
  if(wp_verify_nonce( $_POST['nonce'], ... )){
  ...
  }
}

The word "correct" can be very relative, but the thing is, why would I run wp_verify_nonce() if I don't know the value required by the function is defined at all?

For the generics of this same situation, what is considered to be a better practice?

Aucun commentaire:

Enregistrer un commentaire