tags:

views:

33

answers:

2

I am not strong on my PHP knowledge, but I have never seen this before. In a config file, there are a list of options defined in an array like so:

$testarray[] = "None";
$testarray[] = "Item 1 with normal text";
$testarray[] = "Item 2® with html encoded string";
$testarray[] = "Item3® with another html encoded string";

So now, when the form is generated, it does a simple for each loop to create a list of radio buttons:

foreach ( $testarray as $key=>$item){
echo '<div id="padBottom"><input type="radio" name="formItem"';
    if ( $item == $_SESSION['ss']['selection']) echo ' checked="checked"';
    echo ' value="' . $item. '" />' . $item. '</div>';
}

So far so good, the form generates like it should. The part that is not working is the If statement portion. On the page that this form posts to, it does a simple call to set $_SESSION['ss']['selection'] = $_POST['formItem']; When this happens, the value that goes into session is the actual registered trademark symbol and not '&reg;' as I would expect. As a result, if you select an item with the HTML encoded entity in it, we are not getting a match and your selection appears to be lost. In this example, choosing the first or second option results in the proper radio button being selected - if you choose option 3 or 4, then no selection appears to have been made when you return to this screen.

Addtional info - the charset for this page is UTF-8 if that makes any difference here.

Things I have tried

  1. htmlspecialchars on the POST variable in the next page: result, nothing, still showing actual symbol.
  2. htmlspecialchars on the form value for each radio option: result, I get &amp;reg; as part of my value which doesn't display well.
+2  A: 

Some characters (including ampersands) have special meaning in HTML, you have to represent them as entities if you don't want that special meaning to take effect.

In this case, it is the variable you are inserting into the value attribute that you need to encode.

David Dorward
@David - thanks for the input. I knew it had something to do with html encoding, I just hadn't tried the right combination yet. I tried #1 above and then #2 above with #1 still in place and that didn't work. But just simply html encoding the value and not again on the post worked great. Thanks!
Tommy
+1  A: 

It might work better if you used the index of the item, rather than its contents, as the index is just a number in this case:

foreach ( $testarray as $key=>$item) {
  echo '<div id="padBottom"><input type="radio" name="formItem"';
  if ( $key == $_SESSION['ss']['selection']) echo ' checked="checked"';
  echo ' value="' . $key .'" />' . $item. '</div>';
}
David Knell
Yeah i agree, I would much rather use integer keys than string matching, but alas, that is not what was given to me from the last programmer and I am not about to refactor this steaming pile o' code :)
Tommy