cancel
Showing results for 
Search instead for 
Did you mean: 

Interpreting check boxes in a PHP form

digital
Grafter
Posts: 94
Registered: ‎11-04-2007

Interpreting check boxes in a PHP form

I have a form on a .htm page that uses POST to send to a .php file.
Amongst other inputs such as a text area and a drop-down list, the .htm form has 6 check boxes:
<input type="checkbox" name="multisite[]" value="Site 1">Site 1
<input type="checkbox" name="multisite[]" value="Site 2">Site 2
<input type="checkbox" name="multisite[]" value="Site 3">Site 3
<input type="checkbox" name="multisite[]" value="Site 4">Site 4
<input type="checkbox" name="multisite[]" value="Site 5">Site 5
<input type="checkbox" name="multisite[]" value="Site 6">Site 6
I need to detect that a user has clicked, say, 'Site 1', 'Site 3' and 'Site 4', and send that information as 'Site 1, Site 3, Site 4', along with the rest of the form once it's completed but cannot see how the .php file should process the clicks from the form to get them into the required format.
Anyone able to help in nice easy words?
TIA
17 REPLIES 17
Peter_Vaughan
Community Veteran
Posts: 14,469
Registered: ‎30-07-2007

Re: Interpreting check boxes in a PHP form

First, each of the check boxes needs to have a unique name. So call them check1 -> 6

<input type="checkbox" name="check1" value="Site 1">Site 1
<input type="checkbox" name="check2" value="Site 2">Site 2

When the form is POSTed, only those boxes that are ticked will have associated $_POST entries.
In the .php file you will need to check for the existance of each of the checkbox names to find out if it was ticked e.g.

if(isset($_POST['check1'])) $check1=TRUE;
else $check1=FALSE;
if(isset($_POST['check2'])) $check2=TRUE;
else $check2 = FALSE;

Then if site1 was ticked, $_POST['check1'] will contain whatever you set for value and so on.
Gabe
Community Veteran
Posts: 767
Registered: ‎29-10-2008

Re: Interpreting check boxes in a PHP form

Or you can use array methods. If you name all your checkboxes multisite[], that will be passed as an array of selected elements, so you can, for instance, ask
if(isset($_POST['multisite'])) {
//is Site 4 checked?
echo in_array('Site 4', $_POST['multisite'], true)? "Site 4 is checked.<br>":"Site 4 is not checked<br>";
//what sites are checked?
$whitelist = array('Site 1', 'Site 2', 'Site 3', 'Site 4', 'Site 5', 'Site 6');
foreach($_POST['multisite']  as  $checked)  {
echo in_array($checked, $whitelist, true)? $checked." is checked.<br>":"monkey business<br>";
}
}

Gabe
7up
Community Veteran
Posts: 15,445
Thanks: 1,236
Fixes: 14
Registered: ‎01-08-2007

Re: Interpreting check boxes in a PHP form

I think what you're trying to get at is how to dynamically handle the checkboxes for values you might not be able to predict (IE those created on the fly). Check boxes do not need unique names as Peter suggests - you can as you are already doing submit them as an array and process them dynamically. You don't even need to know the values and do a in_array() check either. Both Gabe and Peters examples assume you know how many checkboxes will be in the form - and in reality you could have hundreds on each page. As long as you know the name of the array being submitted you can process any number of checkboxes dynamically using my method:

//Put $_GET and $_POST into one array for easy access
$_HTTP = $_GET + $_POST;
//Note you don't have to do the above if you don't want - just use $_GET or $_POST below instead
//Check for multisite being an array
if (is_array($_HTTP['multisite']))
  {
  //Get number of items in array
  $Count = count($_HTTP['multisite']);
  //Iterate through array and do something with each submitted item / value
  for ($i = 0; $i < $Count; $i++)
     {
     //Print value of each item in the array just to demonstrate it works
     print $_HTTP['multisite'][$i] .'<br>';
     //Enter into database or do something else
     }
  }

As you can see my code simply loops through the array allowing you to handle any value for any item even if you don't know what the value will be to search for it. As long as you know the name of the array being submitted (EG multisite) then this will work for you.
EDIT: I forgot to say this also works for textboxes and textareas etc which are also submitted using a array_name[]. For example you can have someones name in a textbox called name[] and then their comments in a textarea called comments[]. When processing in php you simply refer both arrays whilst in the loop at the same time by using:

$Name = $_POST['name'][$i];
$Comments = $_POST['comments'][$i];

You're not limited to just checkboxes Wink
I need a new signature... i'm bored of the old one!
Gabe
Community Veteran
Posts: 767
Registered: ‎29-10-2008

Re: Interpreting check boxes in a PHP form

Quote from: okrzynska
Both Gabe and Peters examples assume you know how many checkboxes will be in the form

And are therefore both able to use whitelists rather than relying on sanitizing the input.
Gabe
7up
Community Veteran
Posts: 15,445
Thanks: 1,236
Fixes: 14
Registered: ‎01-08-2007

Re: Interpreting check boxes in a PHP form

Quote from: Gabe
Quote from: okrzynska
Both Gabe and Peters examples assume you know how many checkboxes will be in the form

And are therefore both able to use whitelists rather than relying on sanitizing the input.

Yes but the problem is that the form may not be limited to just 6 items. See below, the OP does say that they need to detect the checked options along with the rest of.. IE there could be upto 100 of them dynamically output by a php form generator.
Quote from: digital
I need to detect that a user has clicked, say, 'Site 1', 'Site 3' and 'Site 4', and send that information as 'Site 1, Site 3, Site 4', along with the rest of the form once it's completed but cannot see how the .php file should process the clicks from the form to get them into the required format.

Using your method requires you to know the name of each and every one. You could store all the names in the session but this then opens the door for some servers which wipe sessions prematurely to screw things up (the server I use does this quite often). It's best simply to handle the form dynamically and then sanitize the form data. Sanitization should be something that you do with every form anyway regardless so its best to get into a good habit.
I need a new signature... i'm bored of the old one!
Gabe
Community Veteran
Posts: 767
Registered: ‎29-10-2008

Re: Interpreting check boxes in a PHP form

You're objecting to whitelisting?
Whitelisting (input must be of a known form) is inherently safer than sanitization (input may not contain elements of suspect form). The best habit to get into is to use whitelisting wherever possible, in preference.
Whitelisting requires not so much that you know every potential value but that you know the exact form of every potential value. How you whitelist depends on the circumstances, but I did think it was worth giving a simple example.
If there are only 6 checkboxes, then it is arguably simplest and most efficient to use a hard-coded whitelist. (Peter's code shows implicit whitelisting. My first example shows the same approach using array notation. My second example loops through the array against an explicit whitelist.)
If the .htm file is generated by a script (an odd way of doing it in php) and may contain an unknown number of checkboxes with values of known form, then we can easily whitelist against a regex (though that's slightly less efficient), but that is not how I read the OP. If I misread the OP, apologies.
Incidentally, if the OP literally just wants a comma-separated string, the simplest way to get that is to use implode on the array - but you would still want to whitelist the array values before you did anything with it.
My second example uses foreach. Your (okrzynska's) example uses for against count to achieve the same result less efficiently. Am I missing something? I'm not sure session storage is directly relevant, but session.gc_maxlifetime is PHP_INI_ALL, so you do have control of that.
Gabe
7up
Community Veteran
Posts: 15,445
Thanks: 1,236
Fixes: 14
Registered: ‎01-08-2007

Re: Interpreting check boxes in a PHP form

No I'm not saying no to whitelisting but what I am saying is that the OP hasn't explicitly said that the form will be limited to just 6 checkboxes. I prefer whitelisting (especially when it comes to email - and yes i have a email work in progress which uses whitelisting for incoming mail) but you must admit it does mean that you have to know what you're adding to the whitelist in the first place Wink Obviously if it is just hardcoded to 6 checkboes then no problem either way but the impression I got was that the OP wanted to know how to handle them dynamically in case there were more (EG say the script pulls out content dynamically from a db). The OPs initial code showed the use of an array[] so I thought I would expand on this.
.htm pages can be generated and parsed by php. While it is unusual it's not something I would rule out as you never know what the persons project is or how their system is setup. Thats why I assumed that its still possible the form is generated dynamically. No apologies needed - we're all just trying to help Wink
You're not missing anything with the foreach() vs for count arguement no. The op asked for something in "nice easy words" so I did it that way with full comments to show it in simple terms and how it works. It might be a line or two less efficient but it does the same job. foreach() still does a similar job internally (it still needs to know how many items are in the array) but you don't see the code for that and thus don't worry about it.
It would be nice to know if we've managed to help though!
I need a new signature... i'm bored of the old one!
Gabe
Community Veteran
Posts: 767
Registered: ‎29-10-2008

Re: Interpreting check boxes in a PHP form

Er ...  Huh  Roll_eyes oh, never mind  Lips_are_sealed
Gabe
Ben_Brown
Grafter
Posts: 2,839
Registered: ‎13-06-2007

Re: Interpreting check boxes in a PHP form

Quote from: okrzynska
foreach() still does a similar job internally (it still needs to know how many items are in the array)...

Not necessarily. In C for example you can traverse an array without knowing how big it is by using pointers, e.g.:

...
/* 'array' is a null terminated array of pointers to chars, we don't know how long it is */
char **a = array;
while (*a != NULL)
{
  printf("%s\n", *a);
  a++;
}
...

As PHP's internals are written in C I'd be pretty surprised if they didn't use this sort of method.
digital
Grafter
Posts: 94
Registered: ‎11-04-2007

Re: Interpreting check boxes in a PHP form

First of all, sorry for the lack of feedback on your (much appreciated) help, but an urgent family trip and then the worst dose of food poisoning I've ever had (thanks to a well know pizza outlet!) has meant that I've only just been able to get back to this.
I think I'm starting to understand!
The arrays are of different sizes, some have six elements, some less, some more.
In the case of
<input type="checkbox" name="multisite[]" value="Site 1">Site 1
<input type="checkbox" name="multisite[]" value="Site 2">Site 2
<input type="checkbox" name="multisite[]" value="Site 3">Site 3
<input type="checkbox" name="multisite[]" value="Site 4">Site 4
<input type="checkbox" name="multisite[]" value="Site 5">Site 5
<input type="checkbox" name="multisite[]" value="Site 6">Site 6
which is in formindex.htm,  I have been able to process the responses in feedback.php using the foreach method...
$othersitename = "Site name: ";
foreach($_POST['sitename'] as $sitenamebox) {
$sitename .= "$sitenamebox, ";
}
and this works well with
$messageproper =
"This message was sent from:\n" .
"$http_referrer\n" .
"------------------------------------------------------------\n" .
"Site choice: $siteschoice\n" .
etc etc further down the feedback.php file.
However, if none of the boxes are checked (and none of them *have* to be) I get an error. As far as I can see, I could use whitelist to confirm the responses are allowed and $count to check that one or more boxes are ticked. The coding for that has me beat, though. Anyone care to help a little further please?
Peter_Vaughan
Community Veteran
Posts: 14,469
Registered: ‎30-07-2007

Re: Interpreting check boxes in a PHP form

It's a bit difficult to follow what you are trying to do with your input's using multisite[] and your example code using something else.
As I said earlier, the form only posts the input box names for those boxes that are ticked. If no boxes are ticked you don't get the array passed at all.
You can use isset($_POST['name']) to check if something was posted to stop the error (which happens because you tried to access a posted variable that does not exist). It returns true if the variable exists, false if not.
If you are using multisite[] the you can use the following (Gabe posted something similar earlier)
if(isset($_POST['multisite']))
{
  // at least one box ticked so process multisite[] with foreach
}
else
{
   // no boxes ticked so process accordingly or error id necessary
}

You should always use isset() on a variable which may or may not be posted to stop any errors occurring. There are ways to turn off the reporting of errors / warning but it good practice to not produce any at all.
7up
Community Veteran
Posts: 15,445
Thanks: 1,236
Fixes: 14
Registered: ‎01-08-2007

Re: Interpreting check boxes in a PHP form

I personally just use the is_array() function. Works for me, no checkbox checked, one checked or a whole bunch checked.

$Test[] = 'test';
if (is_array($Test))
  {
  print 'yes';
  }
else
  {
  print 'no';
  }

http://uk.php.net/is_array
I need a new signature... i'm bored of the old one!
Peter_Vaughan
Community Veteran
Posts: 14,469
Registered: ‎30-07-2007

Re: Interpreting check boxes in a PHP form

But your example will produce an error in the webserver log if $Test does not exist (which is would do if no tick boxes were ticked), which is bad practice. Hence using isset() which does not produce any errors if $Test or whatever array variable is being tested does not exist.
7up
Community Veteran
Posts: 15,445
Thanks: 1,236
Fixes: 14
Registered: ‎01-08-2007

Re: Interpreting check boxes in a PHP form

True.. I don't know why I didn't think of that myself especially when I always use ((isset()) and (is_array())) together. Idiot ain't I...
I need a new signature... i'm bored of the old one!