I have this select input in my form that I want to access via PHP.
<div data-role='fieldcontain'>
<label for='fruits' class='select'>Favorite Fruits</label>
<select name='fruits[]' id='fruits' multiple='multiple' data-native-menu='false'>
<option value=''>Favorite Fruits</option>
<option value='1' selected='selected'>Apple</option>
<option value='2' selected='selected'>Banana</option>
<option value='3' selected='selected'>Cherry</option>
</select>
</div>
By setting the name of the select element to “fruits[]”, this works:
// |$fruits| is an array
$fruits = $_POST['fruits']
However, I am concerned about cleaning data from the form. Feeding post data into an array sounds insecure. What if, for instance, someone changes the select element into a text input element via Firebug and inputs malicious code into my program? I never call htmlspecialchars.
Are my security concerns valid? Why or why not?
They are valid indeed, if the data comes from the user input you need to sanitize it first.
In this case, a user can easily break your HTML or, even worse, inject some malicious XSS attack.
You need to sanitize the values,
htmlspecialcharsis enough in this case.Nevermind, I understood you were populating the HTML select tag with options from user input, but this is not the case. PHP will only accept strings or arrays in POST data, so you need to make sure the data coming in is compatible with what you want to do with it. One possible solution would be to white-list the submitted values, functions like
array_intersectmight be useful here, for instance:This way, if the user submits “Strawberries” it will be ignored on the
$fruitsarray.You might also want to make sure that the array isn’t multidimensional, like this:
This of course, depends on your usage of the data but the white-list approach is always the most secure.