Jimmy Jimmy -4 years ago 148
PHP Question

Send radio selection to function along with textbox

I've got some code working that takes the text from my input box and moves it across to a function. I'm now trying to change it so I add another form element, a radio button and I want to access the choice within my functions.php file.

This is my current code which works for the post name, but what if I want to also grab the colours boxes that was selected too?

main.php

<?php

if (isset($_POST['submit'])) {
$data = $_POST['name']; // the data from the form input.
}

?>

...
<form action="/" method="post">
<input type="text" name="name" placeholder="Acme Corp"/>
<input name="colour" type="radio" value="red">Red<br>
<input name="colour" type="radio" value="blue">Blue<br>
<input name="colour" type="radio" value="green">Green<br>
<input type="submit" name="submit" value="Submit">
</form>
<img src="pngfile.php?data=<?php print urlencode($data);?>"
alt="png php file">


I guess I confused because currently it is calling this:

pngfile.php

<?php
require_once 'functions.php';
$inputData = urldecode($_GET['data']);
process($inputData);
exit;
?>


Which calls functions.php

<?php
function process($inputdata)
{
...


EDIT: What I have tried:

main.php [Change]

$data = $_POST['name'] && $_POST['colour']


But I'm not really sure how to progress. Any help would be appreciated.

Answer Source

Never trust user input. Sanitize and validate your inputs before using them. This can be arranged better, but the basics are still true.

PHP Manual: filter_input_array()

PHP Manual: filter_var_array()

Small Function Library

function sanitizeArray($filterRules)
{
   return filter_input_array(INPUT_POST, $filterRules, true)
}

function validateArray($filteredData, $validationRules)
{
   return filter_var_array($filteredData, $validationRules, true);
}

function checkFilterResults(array $testArray, array &$errors)
{
   if (!in_array(false, $testArray, true) || !in_array(null, $testArray, true)) {
       foreach($testArray as $key => $value)
       {
           $errors[$key] = '';
       }

       return true;
   }

   if ($testArray['name'] !== true) { //You can make a function and do various test.
       $errors['name'] = 'That is not a valid name.'; 
   }

   if ($testArray['clour'] !== true) { //You can make a function and do many test.
       $errors['colour'] = 'That is not a valid colour.'; 
   }

   return false;
}

function processUserInput(array &$filteredData, array $filterRulesArray, array $validationRulesArray, array &$cleanData, array &$errors)
{
    $filteredInput = null;
    $tempData = sanitizeArray($filterRulesArray);

    if (!$checkFilterResults($tempData, $errors)){
        throw new UnexpectedValueException("An input value was unable to be sanitized.");
        //Consider forcing the page to redraw.
    }

    $filteredData = $tempData;
    $validatedData = validateArray($filteredData, $validationRulesArray);

    if (!$checkFilterResults($validatedData, $errors)){
        return false;
    }

    $errors['form'] = ''; 
    $cleanData = $validatedData;
    return true;
}

function htmlEscapeArray(array &$filteredData)
{
    foreach($filteredData as $key => &$value)
    {
        $value = htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8', false);
    }

    return; 
}

Basic Main Line

try {
        $filterRulesArray = [];      //You define this.
        $filteredData     = [];    //A temporary array.

        $validationRulesArray = [];   //You define this.
        $validatedData        = null; //Another temporary array.

        $results   = null;     //Input processing results: true or false.
        $cleanData = null;     //Filtered and validated input array.
        $errors    = [];       //Any errors that have accumulated.

        if (isset($_POST, $_POST['submit'], $_POST['colour']) && !empty($_POST)) {
            $results = processUserInput($filteredData, $filterRulesArray, $validationRulesArray, $cleanData, $errors);
        } else {
            $errors['form'] = "You must fill out the form."
        }

        if ($results === true) {
            $name   = $cleanData['name'];   //You can do what you want.
            $colour = $cleanData['colour']; //You can do what you want.
            //header("Location: http://url.com/registration/thankYou/")
            //exit;
        }

        //Prepare user input for re-display in browser
        htmlEscapeArray($filteredData);
} catch (Exception $e) {
    header("Location: http://url.com/samePage/"); //Force a page reload.
}

Let the form redraw if input processing fails. Use the $errors array to display error messages. Use the $filteredData array to make the form sticky.

<html>
    <head>
        <title>Your Webpage</title>
    </head>
    <body>
        <h1>My Form</h1>
        <form action="/" method="post">

            <!-- Make spots for error messages -->

            <input type="text" name="name" placeholder="Acme Corp" value="PUT PHP HERE"/>

            <!-- No time to display sticky radios! :-) -->
            <input name="colour" type="radio" checked="checked" value="red">Red<br>
            <input name="colour" type="radio" value="blue">Blue<br>
            <input name="colour" type="radio" value="green">Green<br>
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

Tip:

It may be better to submit numbers for radios, as opposed to longer string values like (red, green, blue). Numbers are easier to sanitize and validate. Naturally, then you must translate the input number into its corresponding string. You would do that after validation has finished, but before using the values. Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download