Reputation: 37
I am trying to build the following form:
<form method="post" action="Index.php">
<label>Name </label>
<input name="name" placeholder="Type Here"><br />
</br>
<label>Email </label>
<input name="email" placeholder="Type Here">
<br /></br>
<label style="display:block;">I need some information regarding:</label>
<textarea name="message" placeholder="Type Here"></textarea>
<br />
<label>*What is 2+2? (Anti-spam)</label>
<input name="human" placeholder="Type Here">
<br />
<input id="submit" name="submit" type="submit" value="Submit" style="height:30px;">
</form>
The PHP code:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$from = 'From: TangledDemo';
$to = '[email protected]';
$subject = 'Hello';
$human = $_POST['human'];
$body = "From: $name\n E-Mail: $email\n Message:\n $message";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
if ($_POST['submit']) {
if ($name != '' && $email != '') {
if ($human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Your message has been sent!</p>';
} else {
echo '<p>Something went wrong, go back and try again!</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
} else {
echo '<p>You need to fill in all required fields!!</p>';
}
}
?>
But constantly getting these errors:
Notice: Undefined index: name in C:\xampp\htdocs\bet4info\Index.php on line 19
Notice: Undefined index: email in C:\xampp\htdocs\bet4info\Index.php on line 20
Notice: Undefined index: message in C:\xampp\htdocs\bet4info\Index.php on line 21
Notice: Undefined index: human in C:\xampp\htdocs\bet4info\Index.php on line 25
Notice: Undefined index: submit in C:\xampp\htdocs\bet4info\Index.php on line 29
Notice: Undefined index: submit in C:\xampp\htdocs\bet4info\Index.php on line 35
Notice: Undefined index: submit in C:\xampp\htdocs\bet4info\Index.php on line 38
Why is it so?
Upvotes: 3
Views: 25321
Reputation: 4371
Into this, first you have to check using the isset
function:
if(isset($_POST['name']) && isset($_POST['email']) &&....)
{
// If isset then assign data to variable $name = $_POST['name'],...
}
else
{
// Redirect to the error page
}
As like this, the same for all the variables.
Upvotes: 0
Reputation: 558
Instead of
$name = $_POST['name'];
if ($_POST['submit'] && $human == '4') {
use
$name = isset($_POST['name']) ? $_POST['name'] : '';
if (isset($_POST['submit']) && $human == '4') {
Upvotes: 5