How to validate radio buttons, check boxes and list menu using PHP?

I’m very new to PHP and have manage to accomplish some form validation.

How ever, I’m wondering how can I add PHP form validation to radio buttons, Lists and check boxes?

Any ideas or tutorial will be greatly appreciated.

IC

use there attributes(ex. value, selected… etc) to validate…

I can honestly tell you I know nothing about what you are talking about. I know what value means but don’t have the slightest clues as to how to use them to make validation, do you have an example?

IC


<?php
  if($_Post[]) {
        if($_POST['list'] == -1)
                echo 'Please select one on the List';
         else {
                ............
         }
}
?>


<form method="post">
 <select name="list">
         <option value="-1">Select One</option>
         <option value="1">One</option>
         <option value="2">Two</option>
</select>
<input type="submit" name="submit">
</form>

Your HTML form will look like this:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
	<meta name="author" content="3261706071">

	<title>Untitled 1</title>
</head>
<body>
<form name="frm1" action="action.php" method="post">
	Active ?
	<input type="radio" name="myrdo" value="Y" /> Yes
	<input type="radio" name="myrdo" value="N" /> No
	<br />
	Education:
	<input type="checkbox" name="mychk" value="G" /> Graduate
	<br />
	Country:
	<select name="country">
		<option value="" selected="selected">Select</option>
		<option value="1">USA</option>
		<option value="2">UK</option>
		<option value="3">Canada</option>
	</select>
	<br />
	<input type="submit" name="btnSubmit" value="Submit Form" />
</form>
</body>
</html>

And now the actions.php file should look like this where you can see simple validation is done here:


if($_SERVER['REQUEST_METHOD'] == 'POST'){
	$error_msg = array();
	if(!isset($_POST['myrdo'])){
		$error_msg[] = "No radio buttons were checked.";
	}
	if(!isset($_POST['mychk'])){
		$error_msg[] = "Graguate was checked";
	}
	if(!isset($_POST['country'])){
		$error_msg[] = "No country as selected.";
	}
	
	if(isset($error_msg) && count($error_msg) == 0){
		// do some form processing
	}
	else{
		// redirect to the form again.
	}
}

I hope you can understand it clearly what i have done here… Good luck!

How ever, I’m wondering how can I add PHP form validation to radio buttons, Lists and check boxes?

Adding to Rajugs example, it is critical issue for you that when you accept data from the web, which can be tampered with, that you also check the type of content being returned to you.

Specifically, when you check listboxes, radios etc, then you can be very exact about what you expect to be returned, because you generated their values.

For example in the sample code Rajug wrote for you, $_POST[‘country’] should only return 1, 2 or 3.

It is imperative that you turn country into and integer, and then check it is less that 4 and greater than 0, which is easy to do.


if( isset( $_POST['country'] ){ 
$country_code = (int)$_POST['country']  ;
}else{
// they did not pick a country
// deal with user error
}

if ( $country_code > 3 || $country_code === 0 ) {
// someone willfully changed a country code, 
// deal with attempted crack ... send them away now.
}


That is pretty verbose in order for you to see what is going on, but that is how you have to think.

Not simply, is it filled in? but does it match what I expect?

To find out why this is important google for xss attacks and sql injection for starters, and find yourself a good php security primer, theres loads on the web.

Yes 100% agreed Paul.

That’s why I would suggest to use some frameworks that has already such features and also go for prepared statements (PDO) so that you will at least be safe from some kind of xss and attacks and sql injections. But for the proper messaging to the user, still you need to write some codes yourself.

PDO, 100% with you on that.

I sleep much better now.

Wow! I feel like I just entered a buffet with no one standing infront of me! :D:D.

Well, the way my form is set up, is I do not have nothing in the action field because the form is processed by the php script on the same page as the html.

I’m away but will post the codes when I can get to the computer with the files.

I really do appreciate all your help and efforts.

I just need to post the code so I know we are on the same page.
However, the information posted here looks just right.

Thanks again.

IC

I know this has been explained but I’m still having trouble understanding how to applied this “practically” what was mentioned earlier.
This is just a demo for learning purposes.

Thanks for your patience!

IC

This is the Radio Button section of the form:


# <div class="system">
# <label for="operatingSystem">Operating System.</label>
# </div>
# <div class="operatingSystem">
#  <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Windows Vista" /><span class="radioSpacer">Windows Vista</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Windows XP" /><span class="radioSpacer">Windows XP</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Mac OSX" /><span class="radioSpacer">Mac</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Linux" /><span class="radioSpacer">Linux</span>
#   </div>

This is my complete code, the page is embedded with PHP and does not use the action method, meaning I have the PHP code mixed with the HTML.


# <?php
# session_start(); // At the very top
# // process the email
# if (array_key_exists('send', $_POST)) {
#   $to = 'myemail.com'; // use your own email address
#   $subject = 'Technical Support Inquiry';
#
#    // list expected fields
#   $expected = array('firstName', 'lastName', 'email', 'phoneNumber', 'operatingSyatem', 'productSelection', 'serialNumber', 'reportProblem');
#   // set required fields
#   $required = array('firstName', 'lastName', 'email', 'operatingSyatem', 'productSelection', 'serialNumber', 'reportProblem');
#   // create empty array for any missing fields
#   $missing = array();
#
#    // assume that there is nothing suspect
#   $suspect = false;
#   // create a pattern to locate suspect phrases
#   $pattern = '/Content-Type:|Bcc:|Cc:/i';
#
#     // function to check for suspect phrases
#   function isSuspect($val, $pattern, &$suspect) {
#     // if the variable is an array, loop through each element
#     // and pass it recursively back to the same function
#     if (is_array($val)) {
#       foreach ($val as $item) {
#         isSuspect($item, $pattern, $suspect);
#         }
#       }
#     else {
#       // if one of the suspect phrases is found, set Boolean to true
#       if (preg_match($pattern, $val)) {
#         $suspect = true;
#         }
#       }
#     }
#
#     // check the $_POST array and any sub-arrays for suspect content
#   isSuspect($_POST, $pattern, $suspect);
#
#   if ($suspect) {
#     $mailSent = false;
#     unset($missing);
#     }
#   else {
#     // process the $_POST variables
#     foreach ($_POST as $key => $value) {
#       // assign to temporary variable and strip whitespace if not an array
#       $temp = is_array($value) ? $value : trim($value);
#       // if empty and required, add to $missing array
#       if (empty($temp) && in_array($key, $required)) {
#         array_push($missing, $key);
#         }
#       // otherwise, assign to a variable of the same name as $key
#       elseif (in_array($key, $expected)) {
#         ${$key} = $temp;
#         }
#       }
#     }
#
#       // validate the email address
#   if (!empty($email)) {
#     // regex to ensure no illegal characters in email address
#     $checkEmail = '/^[^@]+@[^\\s\\r\
'";,@%]+$/';
#     // reject the email address if it doesn't match
#     if (!preg_match($checkEmail, $email)) {
#       array_push($missing, 'email');
#       }
#     }
#
#   // go ahead only if not suspect and all required fields OK
#   if (!$suspect && empty($missing)) {
#     // set default values for variables that might not exist
#     $subscribe = isset($subscribe) ? $subscribe : 'Nothing selected';
#     $interests = isset($interests) ? $interests : array('None selected');
#
#         // build the message
#     $message = "First Name: $firstName\
\
";
#     $message .= "Last Name: $lastName\
\
";
#     $message .= "Email: $email\
\
";
#     $message .= "Phone Number: $phoneNumber\
\
";
#     $message .= "Operating System: $operatingSystem\
\
";
#     $message .= "Trouble Product: $productSelection\
\
";
#     $message .= "Serial Number: $serialNumber\
\
";
#     $message .= "Trouble Details: $reportProblem\
\
";
#     // limit line length to 70 characters
#     $message = wordwrap($message, 70);
#
#     // send it
#    $mailSent = mail($to, $subject, $message, 'From: '.$firstName.' '.$lastName.'  <'.$email.'>' );
#    if ($mailSent) {
#    //redirect the page with a fully qualified URL
#    $_SESSION['firstName'] = $firstName;
#    header('Location: http://www.patrickjudson.com/confirmation.php');
#    exit;
#     }
#    }
#   }
# ?>
#
#
# <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
# <html xmlns="http://www.w3.org/1999/xhtml">
# <head>
# <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
# <title>Untitled Document</title>
# <link href="tech_support.css" rel="stylesheet" type="text/css" media="screen" />
# <style type="text/css">
# <!--
# .radioSpacer {
#     padding-right: 8px;
# }
# .style1 {
#     color: #030303;
#     font-size: 11px;
#     width: 176px;
#     display: block;
#     float: left;
#     clear: none;
#     padding-top: 22px;
# }
# -->
# </style>
# </head>
#
# <body>
# <div id="formWrapper">
# <p class="formTitle">Technical Support - Please fill out form completely.</p>
# <form id="support" name="tech_support" class="techsupport_form" method="post" action="">
#
# <!--PERSONAL INFORMATION-->
# <div class="personalInfo">
#
# <div class="name_fieldWrapper">
#   <label for="firstName">First Name: <?php
#                 if (isset($missing) && in_array('firstName', $missing)) { ?>
#                 <span class="warning">Required!</span><?php }
#                 ?>
#         </label>
#   <input type="text" name="firstName" id="first_name" class="name_inputControl"
#   <?php if (isset($missing)) {
#                   echo 'value="'.htmlentities($_POST['firstName']).'"';} ?> />
# </div>
#
# <div class="name_fieldWrapper">
#   <label for="lastName">Last Name: <?php
#                 if (isset($missing) && in_array('lastName', $missing)) { ?>
#         <span class="warning">Required!</span><?php }
#                 ?></label>
#   <input type="text" name="lastName" id="last_name" class="name_inputControl"
#   <?php if (isset($missing)) {
#                   echo 'value="'.htmlentities($_POST['lastName']).'"';} ?> />
# </div>
#
# <div class="email_fieldWrapper">
#   <label for="email">E-mail: <?php
#                 if (isset($missing) && in_array('email', $missing)) { ?>
#                 <span class="warning">Required!</span><?php } ?>
#         </label>
#   <input type="text" name="email" id="email" class="email_inputControl"
#   <?php if (isset($missing)) {
#  echo 'value="'.htmlentities($_POST['email']).'"';} ?> />
# </div>
#
#
# <div class="phone_fieldWrapper">
#   <label for="phoneNumber">Phone Number:
#   <?php
#   $error = '';
#   if(array_key_exists('phoneNumber', $_POST))
#   {
#     if(!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $_POST['phoneNumber']))
#     {
#       $error = 'Invalid Number!';
#     }
#   }
# ?>
#   <span class="warning"> <?php echo $error; ?></span></label>
#   <input name="phoneNumber" type="text" class="phoneNumber_inputControl" id="phoneNumber"
#   <?php if (isset($missing)) {
#                   echo 'value="'.htmlentities($_POST['phoneNumber']).'"';} ?>  />
#
# </div>
# <span class="style1">U.S. Only. Eg: 111-111-111</span></div>
# <!--##############################NEWS LETTER################################-->
# <div class="system">
# <label for="operatingSystem">Operating System.</label>
# </div>
# <div class="operatingSystem">
#  <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Windows Vista" /><span class="radioSpacer">Windows Vista</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Windows XP" /><span class="radioSpacer">Windows XP</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Mac OSX" /><span class="radioSpacer">Mac</span>
#   <input name="operatingSystem" type="radio" class="system_checkBox" id="userSystem" value="Linux" /><span class="radioSpacer">Linux</span>
#   </div>
#
# <!--###################################pPROBLEM REPORT SECTION#############################-->
# <div class="problemProduct">
#  <label for="productSelection"><span class="product_label">Product Name.</span></label>
#  <select name="productSelection" id="products" class="selection">
#    <option value="None">-------------Select a product----------</option>
#    <option value="Everex DVD Burner">Everex DVD Burner</option>
#    <option value="Vidia DVD Burner">Vidia DVD Burner</option>
#    <option value="Excerion Super Drive">Excerion Super Drive</option>
#    <option value="Maxille Optical Multi Burner">Maxille Optical Multi Burner</option>
#    <option value="Pavilion HD Drives">Pavilion HD Drives</option>
#  </select>
#   </div>
#
#  <!--###################################SERIAL NUMBER#############################-->
#
#   <div class="problemProduct">
#   <?php
#   $serialNumbers = array('AB2468101214','123456');
#   $error = (in_array($_POST['serialNumber'], $serialNumbers) && !empty($_POST['serialNumber']))? null : 'A valid Product Serail Number Required!';
# ?>
#  <label for="serialNumber"><span class="product_label">Serial Number.</span></label>
#  <input type="text" name="serialNumber" id="serial" class="serial_numberField"
#  <?php if (isset($missing)) {
#               echo 'value="'.htmlentities($_POST['serialNumber']).'"';} ?> />
#  <span class="warning"> <?php echo $error; ?></span>
#   </div>
#
#    <!--##########################COMMENTS/MESSAGE BOX########################-->
#   <div class="commentBox">
#  <label for="reportProblem">Please explain in detail the problem you are experiencing.
#  <?php
#     if (isset($missing) && in_array('reportProblem', $missing)) { ?>
#     <span class="warning">Required!</span> <?php } ?>
#  </label>
# <textarea name="reportProblem" id="report" cols="56" rows="6" class="textArea_inputControl">
# <?php
# if (isset($missing)) {
# echo htmlentities($_POST['reportProblem']);
# } ?>
# </textarea>
# </div>
#
# <div class="submitForm">
# <input name="send" id="submit" class="submitButton" type="submit" value="Report Problem" />
# <input name="reset" id="cancel" class="submitButton" type="reset" value="Reset Form" />
# </div>
#
# <br class="gForce" />
# </form>
# </div>
# </body>
# </html>

Then what do you want us to do here? This is simple to implement the above code in your case:


if(!isset($_POST['operatingSystem'])){
// throw error here.
}
else{
//continue
}