Using PHP with Radio Buttons.

This is a beginner’s tutorial on how to use the Radio Button HTML element with PHP. In this example, we will be building a HTML form that contains a simple “Yes” / “No” choice. We will then process and validate the radio buttons using PHP.

HTML Radio Buttons.

Let’s take a look at the following HTML form:

The form above simply asks the user if they agree to our website’s Terms & Conditions. Two radio inputs are present in the form and they provide the user with a Yes or No choice.

It is important to note that none of the radio buttons in the form above are ticked by default. If you want to tick a radio button by default, then you will can use the checked attribute:

Now, onto the PHP part!

Processing and validating radio buttons with PHP.

A lot of beginner developers make the mistake of assuming that one of their radio buttons will be ticked. As a result, they end up with nasty undefined index errors.

Simply put: Your PHP code must be able to handle instances where no radio button was submitted. The user might not tick one of your radio buttons or worse: They might open up developer tools and remove the radio buttons altogether.

HTML forms can be easily modified. Therefore, you can never trust the client and you must validate everything.

Let’s take a look at the following PHP example:

A few points above the PHP code above:

  • We set a default option to fall back on if our radio button is not ticked or submitted by the client.
  • Our code checks to see if a radio button value actually exists before attempting to process it. As I said above, if you fail to do this, there’s a good chance that your PHP code with throw undefined index errors.
  • We created a whitelist array of acceptable values. This is important, as a user could modify the values of our radio buttons by using the developer tools feature on Chrome or Firefox. i.e. They could change “yes” to “hello”. Or even worse: They could enter SQL code, JavaScript or spam content in the hope that we store and display the radio input values without validating them.
  • Once our PHP code has validated the radio input correctly, we process the form.

Creating a whitelist of acceptable values is especially important. Could you imagine if a user was able to change “yes” to “helicopter” in your TOS form?

Anyway, I hope you found this tutorial to be helpful!

Facebook Comments