how to keep the state of a check box after server-side validation in PHP?

advertisements

I have a form with various fiedls (Name, email, password, etc..). It also has a set of 5 check-boxes. As i have to update a database i prefer doing server-side validation and i am using php.

If a validation error occurs, the error is displayed on the top of the page along with the form and the previously entered data in the text fields. I am not able to retain the state of the checkboxes and radio buttons. The all revert back to being not selected. What should i do to retain the state of checkboxes and radio buttons?

The form looks something like..:

    Password:<input type="text" name="password" size="16" maxlength="9" value="<?php echo $_POST['password']?>"/>
    Retype Password:<input type="text" name="repassword" value="<?php echo $_POST['repassword']?>"/>
    Select:<br />
    <input type="checkbox" name="option1" value="on1" id="opt1"/> <label for="opt1">Option1</label><br />
    <input type="checkbox" name="option2" value="on2" id="opt2"/> <label for="opt2">Option2</label><br />
    <input type="checkbox" name="option3" value="on3" id="opt3"/> <label for="opt3">Option3</label><br />
    <input type="checkbox" name="option4" value="on4" id="opt4"/> <label for="opt4">Option4</label><br />
    <input type="checkbox" name="option5" value="on5" id="opt5"/> <label for="opt5">Option5</label><br />
    Mobile No:<input type="text" name="mobileno" maxlength="10" value="<?php echo $_POST['mobileno']?>"/>


What you're talking about is Sticky Forms. You can implement sticky forms in many ways, my choice is to use session. If there is an error in your validation, simply dump everything in your POST data into session. On your form page, check to see if the value is set in session and set the default value of the form control it if it is:

Validation Page:

<?php
    session_start();
    if(/** some error condition **/) {
        foreach($_POST as $k => $v)
            $_SESSION['sticky_'.$k] = $v;

        header('Location: http://site.com/yourform.php');
        exit();
    }
?>

Form Page:

<?php session_start(); ?>

<input type = "checkbox" name = "option1" value = "on1" id = "opt1" <?php
    if(isset($_SESSION['sticky_option1']))
        echo('checked = "checked");
?>/>

Example TextBox: <input type = "text" name = "textBoxName" <?php
    if(isset($_SESSION['sticky_textBoxName']))
        echo('value = "' . $_SESSION['sticky_textBoxName'] . '"');
?>

...

<?php
    // Erase the POST values from session after the HTML is constructed.
    foreach($_SESSION as $k => $v)
        if( strpos($k, 'sticky_' !== false )
            unset($_SESSION[$k]);
?>