Hello everyone,
I’m trying to sanitize some data in a form.
The code in the contact form includes the following:
<form name="form1" method="post" action="form-email.php">
<input type="text" name="name" value="<?php echo $_POST['name']; ?>" size="50"
<input type="submit" name="Submit" />
</form>
The code in form-email.php includes:
<?php
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
}
?>
When I open the page which includes the contact form, I receive a notice:
Undefined index: name in C:\wamp\www\site1\contact-us.php on line 11
What does this mean?
Please help – thank you!
Since you haven’t posted any data yet, the following will throw the Notice you received
<?php echo $_POST['name']; ?>
To remedy it
<?php echo (isset($_POST['name'])) ? $_POST['name'] : ''; ?>
Hi cpradio,
that worked!
Thank you very much for your fast reply.
Have a good day.
Hello again,
now I have another problem. When I submit the form I receive a notice:
Undefined variable: errors in C:\wamp\www\site1\form-email.php on line 11
The error corresponds to the error message on line11:
$errors .= ‘Please enter your name.<br/>’;
Why would the variable be undefined?
If someone could help me out. Sorry, but I only have questions…no answers.
Thank you in advance!
Because you never initialized it. Add $errors = array(); above your first if statement and that notice will go away.
Hi cpradio,
sorry, where exactly? Like this?
<?php
$errors = array();
if (isset($_POST['Submit'])) {
if ($_POST['name'] != "") {
$_POST['name'] = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
if ($_POST['name'] == "") {
$errors .= 'Please enter a valid name.<br/><br/>';
}
} else {
$errors .= 'Please enter your name.<br/>';
}
}
?>
When I submit the form, I now don’t receive a notice, but the validation says:
ArrayPlease enter your name.
Yep, my bad. change it to $errors = ‘’;
Okay, thanks a lot. Will try it.
I appreciate your help.
Hi,
it’s working now - thank you!