Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hello! 
Please explain to me how gender validations from scripts 2.3 differ from the nested one in script 2.4.


I have this in 2.3 (updated with NULL coalescing operator while practicing Pursue section):


$gender = $_REQUEST['gender'] ?? NULL; 
   
  if ($gender == 'M') {
    $greeting = '<p><strong>Good day, Sir!</strong></p>';
  } elseif ($gender == 'F') {
    $greeting == '<p><strong>Good day, Madam!</strong></p>';
  } else {
    $gender = NULL;
    echo '<p class="error">Gender must be either "M" or "F"!</p>'; /* You may wonder how this last case 
    may be possible, considering the values are set in the HTML form. 
    If a malicious user creates their own form that gets submitted to your handle_form.php script 
    (which is very easy to do), they could give $_REQUEST[‘gender’] any value they want. */
  }

 

and this in 2.4:


if (isset($_REQUEST['gender'])) {
  $gender = $_REQUEST['gender'];
   
  if ($gender = 'M') {
    $greeting = '<p><strong>Good day, Sir!</strong></p>';
  } elseif ($gender = 'F') {
    $greeting = '<p><strong>Good day, Madam!</strong></p>';
  } else {
    $gender = NULL;
    echo '<p class="error">Gender must be either "M" or "F"!</p>'; /* You may wonder how this last case 
    may be possible, considering the values are set in the HTML form. 
    If a malicious user creates their own form that gets submitted to your handle_form.php script 
    (which is very easy to do), they could give $_REQUEST[‘gender’] any value they want. */
  }
} else { // $_REQUEST['gender'] is not set.
  $gender = NULL;
  echo '<p class="error">You forgot to
  select your gender!</p>';
}

It seems that these scripts do the same job, or I just can't figure out the difference, please help me to understand it.
And also I want to if we could use NULL coalescing operator in script 2.4 some way. Thank you! 

 

Link to comment
Share on other sites

Yes, both versions are comparable with respect to validating the gender. To use the NULL coalescing operator in Script 2.4, you'd probably just write it like your version of Script 2.3 (note that you don't need the $gender = NULL in there though). 

  • Like 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...