I have a php page where users may enter data into fields inside a form.
The form also has a picture upload utility.
This page is refreshed every time a new picture is uploaded, so to ‘remember’ the values the user ALREADY has filled in, I have this code:
<input type="text" value="<?php echo @$_POST['name'];?>">
This DOESN’T work for drop lists or radios…
I have one solution from a previous Q but that would mean I would have to create all drop lists again in PHP, when they are in HTML now, and it is ALOT of options in the drop lists.
Is there any other way?
Here is the first solution:
$color = $_POST["colors"];
$colors = array("red","green","blue");
<select name="colors">
<?php foreach ($colors as $option) { ?>
<option<?php print ($option == $color) ? " selected" : ""; ?>>
<?php print $option; ?>
</option>
<?php } ?>
</select>
Thanks
Sorry to say, but you have to output valid HTML no matter how much of a pain that is. Best suggestion is to wrap it in a helper function and include it. Or even better, go find a good form handling library and use it. This problem has been solved 1000’s of times.
XSS CONCERN: Your example code has a number of security flaws. Let me illustrate a simple way to handle a form cleanly. The following code illustrates an error-proof way to handle:
Please note the use of
htmlspecialcharsandENT_QUOTESwhere needed. Also, the use of thecond ? val1 : val2operator ensures that there are noE_STRICTwarnings omitted, without the use of@(which can be terrible for performance).