PHP Form Variables and POST - HTML Encoded Strings
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:
开发者_如何学JAVAforeach ( $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 '®'
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
- htmlspecialchars on the POST variable in the next page: result, nothing, still showing actual symbol.
- htmlspecialchars on the form value for each radio option: result, I get
&reg;
as part of my value which doesn't display well.
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.
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>';
}
精彩评论