Joansy Joansy - 4 months ago 18
PHP Question

PHP Contact Form Does Not Confirm Sent Message

After a one-page website redesign, I've noticed that the contact form is not working correctly. It accepts input, but then the page doesn't reload. The PHP confirmation messages are also visible even before you click "submit". I also do not get an email with the collected data. I copied this PHP from the previous working contact form in the old version of my website, and am trying to get it to fit into the new code. I've matched up all of the variables and checked it for spelling errors. So far, I don't see any differences in the code, but it obviously doesn't work. ?

In the error log, the code says:

[24-Jan-2015 15:07:54 UTC] PHP Parse error: syntax error, unexpected '{', expecting '(' in /home/website/public_html/index.php on line 664


Listen 664 is the line below that begins "

<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$number = $_POST['number'];
$message = $_POST['message'];
$from = 'From: Contact Form';
$to = 'me@email.com';
$subject = 'Inquiry';

$body = "From: $name\n E-Mail: $email\n Phone: $phone\n Message:\n $message";

if ($name != '' && $email != '')
{
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
{
echo '<p>You need to fill in all required fields.</p>';
}
}
?>


Here is all the contact form:

<div class="col-md-6 contact-form">
<h1>Get In touch</h1>
<div class="contact" data-scroll-reveal="enter left">
<form id="contact-form" action="index.php" method="post">
<ul>
<li>
<input type="text" name="name" id="name" placeholder="Name">
</li>
<li>
<input type="text" name="number" id="number" placeholder="Number">
</li>
<li>
<input type="email" name="email" id="email" placeholder="E-Mail">
</li>
<li>
<textarea name="message" id="message" placeholder="Message"> </textarea>
<input class="btnsend" name="submit" type="submit" id="submit" value="Send">
</li>
</ul>
</form>
</div>
</div>

Answer

Put all your code into the if, as @jeroen said, use isset and you can also put the last else for your if ($name, like:

if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $number = $_POST['number'];
    $message = $_POST['message'];
    $from = 'From: Blue Mountain Website Contact Form'; 
    $to = 'cassidy@blumount.com'; 
    $subject = 'Inquiry';

    $body = "From: $name\n E-Mail: $email\n Phone: $phone\n Message:\n $message";

    if ($name != '' && $email != '') {
        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 {
        echo '<p>You need to fill in all required fields.</p>';
    }
}