Search code examples
phpsanitization

PHP sanitizing location data


I've got this html

<select name="country">
    <option value="Iraq">1</option>
    <option value="Texas">2</option>
    <option value="Paris">3</option>
    ...
    <option value="n">nnn</option>
</select>

There are a really hellish lot of options in this select element and I wouldn't really like to allow people to change the values of any options and I can't stop them from doing that, though, I am curious, is there an efficient PHP way to check if the value legit, for example, I could do this:

<?php
    $country = $_POST['country'];
    if(($country == "Iraq") && ($country == "Texas") && ($country == "Paris) ....($country == "n"))
{
    allow stuff;
}
?>

But that would require a really huge amount of if statements, isn't there another magical way to solve this problem?


Solution

  • Sure, use in_array:

    $countries = ['Iraq','Texas',...];
    if(in_array($_POST['country'], $countries)) {
        // allow stuff
    }
    

    Build your $countries array once, and then use it to generate your <select> HTML code and to validate the submission. Bonus!

    Side note: I need to visit the country of Texas. Didn't realize they seceded!