Regex Validate One Letter Multiple Choice - php

New guy here - I have three choices and want to let the user only pass to the next page "4.html" if they select A, else send them to google.com. This is where I've gotten so far :(
if(empty($_POST['choice'])){
echo "Please select at least one choice..!!";
//this should send them to google.com if they select none or the wrong one
}
else{
foreach($_POST['choice'] as $choice){
header('Location: /4.html');
}
}
<form action="multichoice.php" method="post">
<input id="checkbox" type="checkbox" name="choice[]" value="A" />A)Choice A
<input id="checkbox" type="checkbox" name="choice[]" value="B" />B)Choice B
<input id="checkbox" type="checkbox" name="choice[]" value="c" />C)Choice C
<input id="input"onclick="return myFunction()" type="submit" value="Submit"></input>
</form>
I really appreciate your guys' help!

Sidenote: You can't use echo and header together, otherwise you will be outputting before header.
Consult the link following this (footnotes) and is intended to be run inside the same file:
Checkbox method: (which differs from the radio buttons below)
<?php
if(isset($_POST['submit'])){
if(isset($_POST['choice'])){
foreach($_POST['choice'] as $choice){
if($choice == "A"){
echo "You chose A" . "\n";
// header('Location: /4.html');
// exit;
}
if($choice == "B"){
echo "You chose B" . "\n";
}
if($choice == "C"){
echo "You chose C" . "\n";
}
} // brace for foreach
} // brace for if(isset($_POST['choice']))
// else for if(isset($_POST['choice']))
else{
echo "Please make a choice.";
}
} // brace for if(isset($_POST['submit']))
?>
<form action="" method="post">
<input id="checkbox" type="checkbox" name="choice[]" value="A" />A)Choice A
<input id="checkbox" type="checkbox" name="choice[]" value="B" />B)Choice B
<input id="checkbox" type="checkbox" name="choice[]" value="C" />C)Choice C
<input id="input" onclick="return myFunction()" name="submit" type="submit" value="Submit">
</form>
Radio buttons method: (edited) and added a name attribute to the submit button. Sidenote: </input> isn't a valid tag; it's been removed.
<?php
$choice = $_POST['choice'];
if(isset($_POST['submit'])){
if($choice == "A"){
// echo "You chose A" . "\n";
header("Location: /4.html");
exit; // stop further execution
}
if($choice == "B"){
echo "You chose B" . "\n";
}
if($choice == "C"){
echo "You chose C" . "\n";
}
if(empty($_POST['choice'])){
header("Location: http://www.google.com/");
exit; // stop further execution
}
} // submit conditional
?>
<form action="" method="post">
<input id="radio" type="radio" name="choice" value="A" />A)Choice A
<input id="radio" type="radio" name="choice" value="B" />B)Choice B
<input id="radio" type="radio" name="choice" value="C" />C)Choice C
<input id="input" onclick="return myFunction()" name="submit" type="submit" value="Submit">
</form>
Footnotes:
See the following on the subject of outputting before header:
How to fix "Headers already sent" error in PHP
Also, you can use radio buttons for single choices and without the array.
If you're faced with errors/notices/warnings, somewhere down the line:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.

Related

Undefined index PHP with echo radio buttons value

<h1> Hotel kamer reservering </h1>
<br><br>
<form method="POST">
<input name="radio" type="radio" value="éénpersoonskamer">éénpersoonskamer</input><br><br>
<input name="radio1" type="radio" value="tweepersoonskamer">tweepersoonskamer</input><br><br>
<input name="radio2" type="radio" value="ontbijt">ontbijt</input><br><br><br>
<input name="radio3" type="radio" value="lunch">lunch</input><br><br><br>
<input name="radio4" type="radio" value="diner">diner</input><br><br><br>
<input name="submit" type="submit" <value="Klik"></input>
</form>
<?php
if(isset($_POST['submit']) and ! empty($_POST['submit'])) {
if(isset($_POST['radio']) || ($_POST['radio1']) || ($_POST['radio2']) || ($_POST['radio3']) || ($_POST['radio4']) ) {
$radio = $_POST['radio'] . '&nbsp' . $_POST['radio1'] . '&nbsp' . $_POST['radio2'] . '&nbsp' . $_POST['radio3'] . '&nbsp' . $_POST['radio4'];
echo $radio;
}
}
?>
I am a beginner with PHP, am learning it now but i can't seem to lose the undefined index message. If i choose all then it won't give a bad message. Can someone explain me how i can fix this with this code and how i can resolve it with another code in the future.
I am thankfull for your time.
You're only calling isset() on the $_POST variable for the first radio button. You need to check that all the radio buttons are set. If any of them aren't set, you'll get that warning.
if(isset($_POST['radio'], $_POST['radio1'], $_POST['radio2'], $_POST['radio3'], $_POST['radio4']) ) {
$radio = $_POST['radio'] . '&nbsp' . $_POST['radio1'] . '&nbsp' . $_POST['radio2'] . '&nbsp' . $_POST['radio3'] . '&nbsp' . $_POST['radio4'];
echo $radio;
}
1) Remove typo "<" before "value" in <input name="submit" type="submit" <value="Klik"></input>
2) This is pointless: "empty($_POST['submit']"
3) All radio buttons should have the same name, not "radio1", "radio2" etc., perhaps it would be better to use checkboxes here if you want to be able to select/deselect more than one option
4) The only reason you're getting an error is because you're checking "radio" variable if it exists with isset($_POST['radio']) as for other radio inputs you're only checking if they have any kind of value: ($_POST['radio1']), you should be checking if all of them exist before checking their values :)
A better approach, as I guess you really are looking for a combination of radio- and checkboxes and that you want to output the checked options:
<h1> Hotel kamer reservering </h1>
<br><br>
<form method="POST">
<input name="roomtype" type="radio" checked="checked" value="éénpersoonskamer">éénpersoonskamer <br><br>
<input name="roomtype" type="radio" value="tweepersoonskamer">tweepersoonskamer <br><br>
<input name="food[]" type="checkbox" value="ontbijt">ontbijt <br><br><br>
<input name="food[]" type="checkbox" value="lunch">lunch <br><br><br>
<input name="food[]" type="checkbox" value="diner">diner <br><br><br>
<input name="submit" type="submit">
</form>
<?php
if(!empty($_POST['submit'])) {
echo "roomtype: " . $_POST['roomtype'] . "<br>";
$food = $_POST['food'];
foreach ($food AS $k => $v) {
echo "Food $k = $v<br>";
}
}
?>

show value highest checkbox

I want to find the group of checkbox that user tick the most to something else
please help me!
Thanks.
Here my HTML
<form method="post">
<input type="checkbox" name="group_1[]" value="V1"/>V1
<input type="checkbox" name="group_1[]" value="V2"/>V2
<input type="checkbox" name="group_1[]" value="V3"/>V3
<br>
<input type="checkbox" name="group_2[]" value="V4"/>V4
<input type="checkbox" name="group_2[]" value="V5"/>V5
<input type="checkbox" name="group_2[]" value="V6"/>V6
<br>
<input type="checkbox" name="group_3[]" value="V7"/>V7
<input type="checkbox" name="group_3[]" value="V8"/>V8
<input type="checkbox" name="group_3[]" value="V9"/>V9
<br><br>
<input type="submit" name="submit" />
</form>
PHP
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
if ($group_1 > $group_2 and $group_1 > $group_3) {
echo "Group 1 is highest ";
}
elseif ($group_2 > $group_1 and $group_2 > $group_3) {
echo "Group 2 is highest ";
}
elseif ($group_3 > $group_1 and $group_3 > $group_2) {
echo "Group 3 is highest ";
}
}
?>
i'm new in php so I code "If Else" but i don't want to use this. and one more i don't want to code specific like "$group_1 = count($_POST['group_1']);" i just want to define "name of checkbox" to get value.
all i want is get same result but different code.
I think you could use the max() function to get highest value
Please refer to http://php.net/max
Probably like this:
<?php
if (isset($_POST['submit'])) {
$group_1 = count($_POST['group_1']);
$group_2 = count($_POST['group_2']);
$group_3 = count($_POST['group_3']);
$array = array("Group 1"=>$group_1,"Group 2"=>$group_2,"Group 3"=>$group_3);
$maxIndex = array_search(max($array), $array);
echo $maxIndex;
}
?>

if and else condition not working on session variables?

i need to solve this issue i have two different session variables and i want echo message and radio button name size values in if and else condition via session variable?
Problem is that when i select radio button it should be display size values instead of accessories?
For Example I Want Like This
If Input Values Like Any Number
echo "Accessories"; // It Should Be Display Accessories If
Any Kind Of Numbers Enter.
Else If Radio Select
echo size name // display size whatever choose
from radio button.
Here's my code:
<?php
session_start();
if(isset($_REQUEST['test']))
{
$_SESSION['size1']=$_POST['size'];
$new_sizes=$_SESSION['size1'];
$_SESSION['cid1']=$_POST['cid'];
if(isset($_SESSION['cid1']))
{
echo "Accessories";
}
else
{
echo $new_sizes;
}
}
?>
<form method="post">
<input type="text" name="cid">
<br>
<label for="Small">Small</label>
<input type="radio" name="size" id="Small" value="Small" />
<label for="Medium" >Medium</label>
<input type="radio" name="size" id="Medium" value="Medium"/>
<label for="Large">Large</label>
<input type="radio" name="size" id="Large" value="Large"/>
<label for="Xl">Xl</label>
<input type="radio" name="size" id="Xl" value="Xl"/>
<br>
<input type="submit" name="test" value"Submit">
</form>
Maybe you should try
something like
if(is_numeric($_SESSION['cid1']))
{
echo "Accessories";
}
else
{
echo $new_sizes;
}
Re-Write code like this:
<?php
session_start();
session_destroy();
session_start();
if (empty($_POST) === false) {
if (empty($_POST['size']) === false) {
$_SESSION['size1']=$_POST['size'];
echo $new_sizes = $_POST['size'];
} else if (empty($_POST['cid']) === false) {
$_SESSION['cid1']=$_POST['cid'];
echo "Accessories";
}
}
?>

Submit button returns nothing, value associated with particular page does not increment PHP

Making a simple three question PHP quiz. Each question is displayed on a page of its own, when the submit button is pressed, the variable $number should increment by one and its value determines the current page that is displayed on the user's browser. It appears that somehow this variable is not incrementing correctly -- when the submit button is pressed, the page does not change. I would really like to get this program running. I would imagine this is a relatively simple script for most of you. If someone could assist in getting this to run, it would be greatly appreciated.
<?php
ini_set('session.gc_maxlifetime',900);
session_start();
if($_SESSION['loggedin'] !== 1) {
header('Location: login.php');
exit;
}
if(isset($_SESSION["correct"])){
$correct = $_SESSION["correct"];
} else {
$number = 0;
$correct = 0;
}
// check if which question was submitted
if (isset($_POST['submit'])) {
// set $number = the question that was submitted
$number = $_POST['question'];
switch ($_POST['question']){
case 1:
if ($_POST['answer'] == 'false'){
$correct++; // this answer should be 'false'
break;
}
case 2:
if ($_POST['answer'] == 2){
$correct++;// this answer should be 'PA'
break;
}
case 3:
if ($_POST['answer'] == "lee") {
$correct++;//this answer should be 'lee'
break;
}
}
}
// set the session correct var to our current tally
$_SESSION['correct'] = $correct;
$total_number = 3;
print <<<TOP
<html>
<head>
<title> History Quiz </title>
</head>
<body>
<h3> History Quiz </h3>
TOP;
if ($number == 0){
print <<<FIRST
<p> You will be given $total_number questions in this quiz. <br /><br/>
You will have 15 minutes to complete it. <br /><br/>
You cannot go back to change previous answers.<br /><br/>
Here is your first question: <br /><br />
</p>
<p>1. Abe Lincoln was born in Illinois.</p>
<p>
<label><input type="radio" name="answer" value="true" /> True </label>
<label><input type="radio" name="answer" value="false" /> False </label>
<input type="hidden" name="question" value="1" />
</p>
FIRST;
}
if ($number == 1){
print <<<SECOND
<p>2. In what state was the battle of Gettysburg fought?</p>
<p>
<label><input type="checkbox" name="answer" value="1" /> a) Texas
</label><br/>
<label><input type="checkbox" name="answer" value="2" /> b)
Pennsylvania </label><br/>
<label><input type="checkbox" name="answer" value="3" /> c) Virginia
</label><br/>
<label><input type="checkbox" name="answer" value="4" /> d) West
Virginia </label>
<input type="hidden" name="question" value="2" />
</p>
SECOND;
}
if ($number == 2){
print <<<THIRD
<p>3. The last name of the commander of the Army of North Virginia was __________.</p>
<p>
<input type='text' id='answer' />
<input type="hidden" name="question" value="3" />
</p>
THIRD;
}
if ($number >= $total_number)
{
print <<<FINAL_SCORE
Your final score is $correct correct out of $total_number. <br /><br />
Thank you for playing. <br /><br />
FINAL_SCORE;
session_destroy();
}
else {
$number++;
$_SESSION['number'] = $number;
$script = $_SERVER['PHP_SELF'];
print <<<FORM
<form method = "post" action = $script>
<input type = "submit" value = "Check Answer" />
</form>
FORM;
}
?>
UPDATE:
<?php
ini_set('session.gc_maxlifetime',900);
session_start();
if($_SESSION['loggedin'] !== 1) {
header('Location: login.php');
exit;
}
if(isset($_SESSION["correct"]) and isset($_SESSION["number"])){
$correct = $_SESSION["correct"];
$number = $_SESSION["number"];
} else {
$number = 0;
$correct = 0;
}
// check if which question was submitted
if (isset($_POST['submit'])) {
// set $number = the question that was submitted
$number = $_SESSION['number'];
switch ($_POST['question']){
case 1:
if ($_POST['answer1'] == 'false'){
$correct++; // this answer should be 'false'
break;
}
case 2:
if ($_POST['answer2'] == "PA"){
$correct++;// this answer should be 'PA'
break;
}
case 3:
if ($_POST['answer3'] == "lee") {
$correct++;//this answer should be 'lee'
break;
}
}
}
// set the session correct var to our current tally
$_SESSION['correct'] = $correct;
$total_number = 3;
print <<<TOP
<html>
<head>
<title> History Quiz </title>
</head>
<body>
<h3> History Quiz </h3>
TOP;
$script = $_SERVER['PHP_SELF'];
if ($number == 0){
print <<<FIRST
<p> You will be given $total_number questions in this quiz. <br /><br/>
You will have 15 minutes to complete it. <br /><br/>
You cannot go back to change previous answers.<br /><br/>
Here is your first question: <br /><br />
</p>
<p>1. Abe Lincoln was born in Illinois.</p>
<p>
<form method = "post" action = "$script">
<label><input type="radio" name="answer1" value="true" /> True </label>
<label><input type="radio" name="answer1" value="false" /> False </label>
<input type="hidden" name="question" value="1" />
<input type = "submit" name = "submit" value = "Check Answer" />
</form>
</p>
FIRST;
}
if ($number == 1){
print <<<SECOND
<p>2. In what state was the battle of Gettysburg fought?</p>
<p>
<form method = "post" action = "$script">
<label><input type="radio" name="answer2" value="Texas" /> a) Texas
</label><br/>
<label><input type="radio" name="answer2" value="PA" /> b)
Pennsylvania </label><br/>
<label><input type="radio" name="answer2" value="Vir" /> c) Virginia
</label><br/>
<label><input type="radio" name="answer2" value="West" /> d) West
Virginia </label>
<input type="hidden" name="question" value="2" />
<input type = "submit" name = "submit" value = "Check Answer" />
</form>
</p>
SECOND;
}
if ($number == 2){
print <<<THIRD
<p>3. The last name of the commander of the Army of North Virginia was __________.</p>
<p>
<form method = "post" action = "$script">
<input type='text' id='answer3' />
<input type="hidden" name="question" value="3" />
<input type = "submit" name = "submit" value = "Check Answer" />
</form>
</p>
THIRD;
}
if ($number >= $total_number)
{
print <<<FINAL_SCORE
Your final score is $correct correct out of $total_number. <br /><br />
Thank you for playing. <br /><br />
FINAL_SCORE;
session_destroy();
}
else {
$number++;
$_SESSION['number'] = $number;
}
?>
First, I just have to ask you why you're using HEREDOC. I've never seen someone do it that way.
Anyways, a few things I noticed:
All of your input fields are being printed above and outside of your form, not sure if that it intentional, but it appears that it is not. Only things inside the actual form will be submitted with that form. Your form needs to surround all of your input fields that you want sent with it and your submit button.
Your submit button has no name. You can't retrieve the value of the submit button unless you name it 'submit', for example. Thus isset($_POST['submit']) will always return false because there is no field with the name 'submit'.
Your action = $script statement should still include quotations around $script for HTML syntax reasons, otherwise you'll get something like action=/path/to/file.
What #MrTrick said should help you as well, although that won't kill your script.
For your answers, you are incorrectly using the checkbox type. You should be using the radio type so that only one option can be selected.
Looking at your program flow; If $_SESSION['correct'] is set, then no value is ever assigned to $number.
Maybe it should be:
if(isset($_SESSION["correct"]) and isset($_SESSION["number"])){
$correct = $_SESSION["correct"];
$number = $_SESSION["number"];
} else {
$number = 0;
$correct = 0;
}
If you have PHP error logging set to STRICT, it should have reported a Notice error where you check the value of $number without having set it to anything.

PHP Form Processing Order precedence

Am new to the world of development and am just starting to pick up PHP. I have basic form that attempts to validate the checkboxes the user has selected or checked. My code is below. The question I have is why is that when I have the order of my form as follows, the form does not pass the value NET, PHP or RUBY and the values that are costantly passed are no.
--- Form code that does not work ---
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="hidden" name="ch3" value="no">
<input type="submit" name="submit" value="submit">
However if my code is as follows;
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch3" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
The boxes appear checked. The entire code below.
<?php
$ch1status = "unchecked";
$ch2status = "unchecked";
$ch3status = "unchecked";
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
if($_POST["ch1"] == "net") {
$ch1status = "checked";
}
}
if(isset($_POST["ch2"])) {
if($_POST["ch2"] == "php") {
$ch2status = "checked";
}
}
if(isset($_POST["ch3"])) {
if($_POST["ch3"] == "ruby") {
$ch3status = "checked";
}
}
if ($_POST["ch1"] == "no" && $_POST["ch2"] == "no" && $_POST["ch3"] == "no") {
print "There is no such choice";
}
}
?>
<html>
<head>
<title>Sample form checkbxoes</title>
</head>
<body>
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="hidden" name="ch1" value="no">
<input type="checkbox" name="ch1" value="net" <?php print $ch1status ?>>.NET
<input type="hidden" name="ch2" value="no">
<input type="checkbox" name="ch2" value="php" <?php print $ch2status ?>>PHP
<input type="hidden" name="ch3" value="no">
<input type="checkbox" name="ch3" value="ruby" <?php print $ch3status ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
print $_POST["ch1"];
print $ch1status;
}
if(isset($_POST["ch2"])) {
print $_POST["ch2"];
print $ch2status;
}
if(isset($_POST["ch3"])) {
print $_POST["ch3"];
print $ch3status;
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
</body>
</html>
</form>
Also is there any other way of validating if the user has not selected any checkboxes as opposed to using hidden form fields.
Its just a browser-issue and its quite simple: The elements have the same name and the later element overwrites the first one.
Another way of validating, if a checkbox is not checked is to check, if its set in the $POST-array. If its missing, its treated like "not checked".
UNDEFINED INDEXES:
This is because checkboxes are only sent if they are checked. One thing you can do is always check the variable with isset (e.g. isset($_POST['ch1'])) before using them; another is to name your checkboxes the same thing with a [] following the name (e.g. name="languages[]") and then do something like this:
// Create a list of languages that are OK (remember, some users are malicious)
$languages = array('net','php','ruby');
// Compile a list of the answers the user picked; force it to be an
// array by either explicitly casting to an array, or using an empty array
// if none chosen
$picked = isset($_POST['languages']) ? (array)$_POST['languages'] : array();
// first, use array_intersect to remove entries present in one and not the other
// i.e. invalid entries from the client or entries not picked from the whole list
// then, "flip" the array so that the values become keys,
// because isset is faster than in_array
$valid_langs = array_flip(array_intersect($languages, $picked));
// check on languages
if (isset($valid_langs['php'])) { /* PHP picked */ }
if (isset($valid_langs['net'])) { /* NET picked */ }
if (isset($valid_langs['ruby'])) { /* Ruby picked */ }
Simpler Solution:
<form>
<input type="checkbox" name="php" value="yes" />
<input type="checkbox" name="net" value="yes" />
<input type="checkbox" name="ruby" value="yes" />
</form>
<?php
$php = $net = $ruby = 'unchecked';
if (!isset($_POST['php'],$_POST['net'],$_POST['ruby'])) {
echo 'There is no such choice';
}
else {
if (isset($_POST['php']) && $_POST['php'] == 'yes') {
$php = 'checked';
}
if (isset($_POST['net']) && $_POST['new'] == 'yes') {
$net = 'checked';
}
if (isset($_POST['ruby']) && $_POST['ruby'] == 'yes') {
$ruby = 'checked';
}
}
// ... snip ...
There are a great many ways to do this. Hopefully you will be interested in learning many of them.
Php is all server-side, so in order to keep them from submitting you'll need client-side validation. Easiest client-side validation is with javascript, or jQuery's Validation Plugin if you're already using jQuery (which you should be if you plan on using AJAX at any point).
And yes, you can get rid of those hidden inputs.
You do not need those hidden fields. Remove them and it should work.
EDIT:
Check out this modification
$ch1status = "unchecked";
$ch2status = "unchecked";
$ch3status = "unchecked";
if(isset($_POST["submit"])) {
if(#$_POST["ch1"] != "") {
$ch1status = "checked";
}
if(#$_POST["ch2"] != "") {
$ch2status = "checked";
}
if(#$_POST["ch3"] != "") {
$ch3status = "checked";
}
if (#$_POST["ch1"] . #$_POST["ch2"] . #$_POST["ch3"] == "") {
print "There is no such choice";
}
}
?>
<html>
<head>
<title>Sample form checkbxoes</title>
</head>
<body>
<form name="checkboxes" method="post" action="form_sample_checkboxes.php">
<input type="checkbox" name="ch1" value="net" <?php echo $ch1status; ?>>.NET
<input type="checkbox" name="ch2" value="php" <?php echo $ch2status; ?>>PHP
<input type="checkbox" name="ch3" value="ruby" <?php echo $ch3status; ?>>Ruby on Rails
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST["submit"])) {
if(isset($_POST["ch1"])) {
print $_POST["ch1"];
print $ch1status;
}
if(isset($_POST["ch2"])) {
print $_POST["ch2"];
print $ch2status;
}
if(isset($_POST["ch3"])) {
print $_POST["ch3"];
print $ch3status;
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
</body>
</html>

Categories