Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

PHP form not working...

I had built a form with bootstrap v3 framework and implemented php validation. It is not working...not sending email and not showing up my "success" or "fail" message after submit is pressed. Should I post my code or the address: http://www.nalldirections.com/contact.php

<?php
    if ($_POST["submit"]) {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $message = $_POST['message'];
        $human = intval($_POST['human']);
        $from = 'Demo Contact Form'; 
        $to = 'gorspi_bboy@yahoo.com'; 
        $subject = 'Message from Contact Demo ';

        $body ="From: $name\n E-Mail: $email\n Message:\n $message";
        // Check if name has been entered
        if (!$_POST['name']) {
            $errName = 'Please enter your name';
        }

        // Check if email has been entered and is valid
        if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $errEmail = 'Please enter a valid email address';
        }

        //Check if message has been entered
        if (!$_POST['message']) {
            $errMessage = 'Please enter your message';
        }
        //Check if simple anti-bot test is correct
        if ($human !== 5) {
            $errHuman = 'Your anti-spam is incorrect';
        }
        // If there are no errors, send the email
        if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
            if (mail ($to, $subject, $body, $from)) {
                $result='<div class="alert alert-success">Thank You! I will be in touch</div>';
            } else {
                $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
            }
        }
            }
        ?>
<form class="form-horizontal" role="form" action="contact.php">
                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">Name</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="name" placeholder="Enter Your Name" value="<?php echo htmlspecialchars($_POST['name']); ?>">
                            <?php echo "<p class='text-danger'>$errName</p>";?>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="email" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-6">
                            <input type="email" class="form-control" id="email" placeholder="name@email.com" value="<?php echo htmlspecialchars($_POST['email']); ?>">
                            <?php echo "<p class='text-danger'>$errEmail</p>";?>
                            <?php echo "<p class='text-danger'>$errEmail</p>";?>
                        </div>
                    </div>

                    <!-- Message area -->
                    <div class="form-group">
                        <label for="message" class="col-sm-2 control-label">Message</label>
                        <div class="col-sm-6">
                            <textarea class="form-control" rows="4" placeholder="Leave us a message..."><?php echo htmlspecialchars($_POST['message']);?></textarea>
                            <?php echo "<p class='text-danger'>$errMessage</p>";?>
                        </div>
                    </div>


                    <!-- Human Validation -->
                    <div class="form-group">
                        <label for="human" class="col-sm-2 control-label">2 + 3 = ?</label>
                        <div class="col-sm-6">
                            <input type="text" class="form-control" id="human" name="human" placeholder="Your Answer, please">
                            <?php echo "<p class='text-danger'>$errHuman</p>";?>
                        </div>
                    </div>

                    <!-- Submit button -->
                    <div class="form-group">                        
                        <div class="col-sm-offset-2 col-sm-6">
                            <button id="submit" type="submit" value="send" class="btn btn-primary">Submit</button>
                            <button id="reset" type="reset" value="reset" class="btn btn-default">Clear</button>
                        </div>
                    </div>

                    <div class="form-group">                        
                        <div class="col-sm-offset-2 col-sm-6">
                            <?php echo $result; ?>
                        </div>
                    </div>

                    <p class="col-sm-offset-2 col-sm-6"><strong>*Please include the best time to call you.<br/>*Please keep in mind we are on the West Coast.</strong></p>

                </form>

6 Answers

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

You have quite a few problems. First of all you need to specify your form method as POST (on your form) since you are checking $_POST in your PHP. Second of all you need to provide a name attribute on your form inputs (submit, email, message, name). The only one you supplied is "human". I don't think you ever make it into your first if block. You can try echoing out strings in blocks to verify that you are actually entering them as you are developing your code. Anyway, those fixes should get you to the mail block although I'm not sure your mail will actually be sent. I never specified my headers the way you do with $from so I don't know if that would work. I usually did something like this:

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: me@mydomain.com\r\n";
$headers .= "Reply-To: me@mydomain.com\r\n";
$headers .= "X-Mailer: PHP \r\n";

if( mail($to, $subject, $message, $headers) ){
...do something
}else{
...do something else
}

Plus on my server my domain in my from address has to match my actual domain (it's an anti spam thing I believe) so you may have to use an @nalldirections.com address. Good luck.

Thanks, I was following a tutorial and this is what was provided. I will work on it and update if I am able to get it to work. Thanks for taking the time to look. I'll let you guys know, Mark C

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

no problem. I actually did make the changes so I know it works. I'm not sending the form though, just printing out what would be sent. http://www.bonvon.com/treehouse/phpform/

LaVaughn... It works! I've sent a couple emails and it sent. Now, there is one more thing that has occurred with each submitted form. Each form sent got emailed twice. Is it because I have an "submit" as an id and a type?

LaVaughn Haynes
LaVaughn Haynes
12,397 Points

That sounds more like a double-submission issue. I think that's common. There are multiple ways to approach that (JavaScript, redirects, cookies, sessions, database). This post might give you some ideas. http://technoesis.net/prevent-double-form-submission/ Think about what might work best for your site. for example, if you chose JavaScript, I personally don't like the idea of disabling submit because what if there is a legit reason for submitting again? You could maybe disable it for 3 seconds only Or disable and redirect, but if they don't have js enabled they can still double submit anyway. Is that acceptable? And so on and so on.

I'm not very familiar with php, but looking at the code. Does the second line:

if ($_POST["submit"]) { 

and:

if (mail ($to, $subject, $body, $from)) {   

-toward the bottom both tell the form to send the information? I'm trying to understand the code by reading the actions, but not enough knowledge to understand completely.

Does anyone think that might be the cause of the form being submitted twice?