Forum Moderators: coopster
<?php echo (isset($_POST['name']) ? $_POST['name'] :'');?>
<?php echo (isset($_POST['name']))? htmlentities($_POST['name'], ENT_QUOTES) : ''; ?>
strip_tags($_POST['name'])
foo"bar
<input type="text" name="foo" value="foo"bar">
<?php
//
// For the sake of demonstration (and in all best possible worlds)
// let's say all your form fields are the same. Yeah right!
$formvars = Array (
'first_name' => (isset($_POST['first_name']))?$_POST['first_name']:null,
'last_name' => (isset($_POST['last_name']))?$_POST['last_name']:null,
'email' => (isset($_POST['email']))?$_POST['email']:null
);
//
/ Most PHP coders would rather use PHP functions, but using regexps
// helps you to iterate through the array for cleansing,
// keeping only what you WANT.
$allowed = Array (
'first_name' => '\w\s\d\-\'\"\&\;',
'last_name' => '\w\s\d\-\'\"\&\;',
'email' => '\w\s\d\-\_\@\.'
);
//
// Now in our perfect world, associate some labels.
$labels = Array (
'first_name' => 'First Name',
'last_name' => 'Last Name',
'email' => 'Email Address',
);
//
// Cleanse and set the data
foreach ($formvars as $key=>$value) {
if ($formvars[$key]) { // might be null
$formvars[$key] = htmlspecialchars(preg_replace("/[^$allowed[$key]]+/i",'',$formvars[$key]));
}
}
//
// Do the form. I am not a fan of mixing and
// matching HTML/progamming, starting/stopping parsing.
$out = '
<form action="formvars.php" method="post">
';
foreach ($formvars as $key=>$value) {
$out .= '
<p><label for="' . $key . '">' . $labels[$key] .
'</label> <input type="text" name="' . $key . '" id="' . $key . '" value="' . $value . '"></p>';
}
$out .= '<input type="submit" value="Submit">';
//
// Output once
header("content-type:text/html");
echo $out;
?>
Which could cause problems.
[edited by: rocknbil at 10:16 pm (utc) on May 24, 2010]