I'm finishing up a small contact form and had a question about providing default values for $_POST
. The reason I'm asking about default values is because within 开发者_开发问答my form I have fields like this:
<input type="text" name="fullname" value="<?php echo $_POST['fullname']; ?>" />
Clearly I would like to retain the submitted value if I do not permit the data to clear. This raises errors when the page is first loaded, since there is no value for $_POST['fullname']
.
To my question: is there anything I should be concerend about providing default values to the $_POST
array like I'm doing in the next code-sample:
$_POST += array(
'fullname' = '',
);
If $_POST['fullname']
already exists, it will be retained - if it doesn't, it will be created within the array. This way, upon loading the form, blank values will be presented in the input fields.
Don't worry, all I sanitize my data Thank you for the help
Even if you are doing so, put that data in your container, do not modify superglobals. Create class that'll contain your data - then you'll have the interface do sanitize, manipulate and get it te proper way. Import data from $_POST and then validate, if all necessary values are in.
As for code:
<?php
class PostData
{
private $data;
public function __construct(array $data)
{
$this->data = is_array($data)
? $data
: array();
}
public function set($key, $value)
{
$this->data[$key] = $value;
}
public function get($key, $default, $escaping)
{
if(isset($this->data[$key]))
{
switch($escaping)
{
case 'htmlspecialchars':
{
return htmlspecialchars($this->data[$key]);
break;
}
case 'mysql_real_escape_string':
{
return mysql_real_escape_string($this->data[$key]);
break;
}
// and so on, your invention goes here
default:
{
return $this->data[$key];
}
}
}
else
{
return $default;
}
}
}
$postData = new PostData($_POST);
Create function:
function displayValue($field) {
if(isset($_POST[$field])) {
echo 'value="' . htmlentities($_POST[$field]) . '"';
}
}
And then use like:
<input type="text" name="fullname" <?php displayValue('fullname'); ?> />
You can also do it like this:
<?php echo empty($_POST['fullname']) ? null : $_POST['fullname']; ?>
精彩评论