Handling Radio Button Values in PHP with Practical Examples

In web development, it’s important to handle user select (Option) input securely to prevent vulnerabilities such as Cross-Site Scripting (XSS) attacks. One common scenario involves using radio buttons and select dropdowns in forms. This blog post will show you how to use htmlspecialchars() in PHP to sanitize this input before displaying it on your website.

Scenario: Choosing a Favorite Color and Rating It

In this example, we’ll create a form where users can choose their favorite color using radio buttons and then rate how much they like it using a select dropdown. We’ll use htmlspecialchars() to ensure the input is safe to display.

Step 1: Create the HTML Form

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Favorite Color Survey</title>
</head>
<body>

<h2>Tell Us About Your Favorite Color</h2>
<form method="POST" action="">
    <p>Choose your favorite color:</p>
    <label>
        <input type="radio" name="color" value="red"> Red
    </label><br>
    <label>
        <input type="radio" name="color" value="blue"> Blue
    </label><br>
    <label>
        <input type="radio" name="color" value="green"> Green
    </label><br>

    <p>How much do you like this color (1 to 5)?</p>
    <select name="rating">
        <option value="1">1 - Not much</option>
        <option value="2">2 - It's okay</option>
        <option value="3">3 - I like it</option>
        <option value="4">4 - I really like it</option>
        <option value="5">5 - It's my favorite!</option>
    </select><br><br>

    <input type="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $color = htmlspecialchars($_POST['color'] ?? 'None selected', ENT_QUOTES, 'UTF-8');
    $rating = htmlspecialchars($_POST['rating'] ?? 'No rating', ENT_QUOTES, 'UTF-8');

    echo "<h3>Your Favorite Color and Rating</h3>";
    echo "Favorite Color: $color<br>";
    echo "Rating: $rating/5";
}
?>


</body>
</html>

Explanation:

  1. HTML Form:
  • The form contains a set of radio buttons allowing the user to select their favorite color (Red, Blue, or Green).
  • There is also a select dropdown where the user can rate how much they like the selected color, on a scale of 1 to 5.
  • Key Points:
    • htmlspecialchars() with ENT_QUOTES, 'UTF-8': Ensures that both single and double quotes are escaped and that the character encoding is set to UTF-8, providing security and compatibility across different languages.
    • Null Coalescing Operator (??): Provides a default value if $_POST['color'] or $_POST['rating'] is not set, making the code concise and avoiding undefined index errors.

Example User Input and Output:

  • User Input:
  • Favorite Color: Blue (selected via radio button)
  • Rating: 4 (selected from the dropdown)
  • Output:
  Favorite Color: Blue
  Rating: 4/5
  • User Input with Malicious Attempt:
  • Favorite Color: <script>alert('XSS');</script> (Attempted via a manipulated form submission)
  • Rating: 5
  • Output:
  Favorite Color: &lt;script&gt;alert(&#039;XSS&#039;);&lt;/script&gt;
  Rating: 5/5

As you can see, the use of htmlspecialchars() ensures that the user input is safe to display, preventing any embedded scripts from executing. This example illustrates how you can securely handle and display user input from radio buttons and select dropdowns in PHP.

Conclusion

Using htmlspecialchars() is a simple yet effective way to protect your web applications from XSS attacks. By sanitizing user inputs before displaying them, you can ensure that your website remains secure and that your users’ data is handled safely.

2. Choosing a Payment Method

One common use case for radio buttons is allowing users to select a payment method.

HTML Form:

<form method="POST" action="process_payment.php">
    <label>
        <input type="radio" name="payment_method" value="credit_card"> Credit Card
    </label><br>
    <label>
        <input type="radio" name="payment_method" value="paypal"> PayPal
    </label><br>
    <label>
        <input type="radio" name="payment_method" value="bank_transfer"> Bank Transfer
    </label><br>
    <input type="submit" value="Proceed to Payment">
</form>

PHP Code (process_payment.php):

<?php
if (isset($_POST['payment_method'])) {
    $payment_method = $_POST['payment_method'];

    switch ($payment_method) {
        case 'credit_card':
            echo "You chose to pay with Credit Card.";
            // Implement Credit Card payment processing here
            break;
        case 'paypal':
            echo "You chose to pay with PayPal.";
            // Implement PayPal payment processing here
            break;
        case 'bank_transfer':
            echo "You chose to pay via Bank Transfer.";
            // Implement Bank Transfer payment processing here
            break;
        default:
            echo "Invalid payment method selected.";
    }
} else {
    echo "No payment method selected.";
}
?>

This example allows users to select a payment method, and based on the selection, the PHP script processes the payment accordingly.

2. Selecting a Shipping Option

Radio buttons are also often used to select shipping options during checkout.

HTML Form:

<form method="POST" action="process_shipping.php">
    <label>
        <input type="radio" name="shipping_option" value="standard"> Standard Shipping
    </label><br>
    <label>
        <input type="radio" name="shipping_option" value="express"> Express Shipping
    </label><br>
    <label>
        <input type="radio" name="shipping_option" value="overnight"> Overnight Shipping
    </label><br>
    <input type="submit" value="Select Shipping">
</form>

PHP Code (process_shipping.php):

<?php
if (isset($_POST['shipping_option'])) {
    $shipping_option = $_POST['shipping_option'];

    switch ($shipping_option) {
        case 'standard':
            echo "You selected Standard Shipping.";
            // Calculate and display standard shipping cost
            break;
        case 'express':
            echo "You selected Express Shipping.";
            // Calculate and display express shipping cost
            break;
        case 'overnight':
            echo "You selected Overnight Shipping.";
            // Calculate and display overnight shipping cost
            break;
        default:
            echo "Invalid shipping option selected.";
    }
} else {
    echo "No shipping option selected.";
}
?>

This example demonstrates how to handle different shipping options based on the user’s selection. The script can calculate shipping costs or handle other logistics.

3. Feedback Form with Rating

Another practical example is collecting feedback from users with a rating system.

HTML Form:

<form method="POST" action="process_feedback.php">
    <p>Please rate our service:</p>
    <label>
        <input type="radio" name="rating" value="1"> 1
    </label><br>
    <label>
        <input type="radio" name="rating" value="2"> 2
    </label><br>
    <label>
        <input type="radio" name="rating" value="3"> 3
    </label><br>
    <label>
        <input type="radio" name="rating" value="4"> 4
    </label><br>
    <label>
        <input type="radio" name="rating" value="5"> 5
    </label><br>
    <input type="submit" value="Submit Feedback">
</form>

PHP Code (process_feedback.php):

<?php
if (isset($_POST['rating'])) {
    $rating = $_POST['rating'];
    echo "Thank you for rating us " . htmlspecialchars($rating) . " out of 5.";
    // Store the rating in the database, send an email, etc.
} else {
    echo "No rating selected.";
}
?>

This example allows users to provide a rating for a service. The PHP script captures the rating and can further process it, such as saving it to a database or sending a thank-you email.

4. Selecting a Newsletter Subscription Preference

You can also use radio buttons to allow users to opt in or out of a newsletter subscription.

HTML Form:

<form method="POST" action="process_subscription.php">
    <p>Would you like to receive our newsletter?</p>
    <label>
        <input type="radio" name="subscribe" value="yes"> Yes, subscribe me.
    </label><br>
    <label>
        <input type="radio" name="subscribe" value="no"> No, thank you.
    </label><br>
    <input type="submit" value="Submit">
</form>

PHP Code (process_subscription.php):

<?php
if (isset($_POST['subscribe'])) {
    $subscribe = $_POST['subscribe'];

    if ($subscribe == 'yes') {
        echo "Thank you for subscribing to our newsletter!";
        // Add the user to the newsletter list
    } elseif ($subscribe == 'no') {
        echo "You have opted out of the newsletter.";
        // Ensure the user is not subscribed
    } else {
        echo "Invalid option selected.";
    }
} else {
    echo "No preference selected.";
}
?>

This example lets users choose whether or not they want to subscribe to a newsletter. The PHP script then processes their choice accordingly.

Conclusion

These examples demonstrate common use cases for radio buttons in PHP forms, including handling payment methods, shipping options, feedback ratings, and newsletter subscriptions. By following these examples, you can effectively capture and process user input from radio buttons in your PHP projects.

Recent Post

As the leading website development agency in Mumbai, our mission is to empower your business with a robust online presence that stands out and converts. Partner with us to take your website to the next level and turn your visitors into loyal customers.


© 2024 All right reserved by Go1Digital.com