Search code examples
phpmail-form

php mail form doesn't work


I think I fixed this. This was the original:

<?php
    if(isset($_POST['email'])) {

    $email = $_POST['email'];
    $name = $_POST['name'];
    $message = $_POST['message'];;
    $subject = $email = $_POST['subject'];;

    $email_to = $email;
    $header = 'From: 1totheN <website@1tothen.com>' . "\r\n";
    function clean_text($string) {
    $bad = array("content-type","bcc:","to:","cc:","href");
    return str_replace($bad,"",$string);
    }
    $email_message .= "Name: ".clean_text($email)."\n";
    $email_message .= "Email: ".clean_text($email)."\n";
    $email_message .= "Message: ".clean_text($message)."\n";
    @mail($email_to, $subject, $email_message, $header);
    echo "Your message has been sent.";

}
?>

Here's the markup on the HTML page:

<form class="contact-form" id="subscribeForm" action="mail.php" method="post">
       <input type="text" name="name" class="required" placeholder="YOUR NAME">
       <input type="text" name="email" class="required email" placeholder="EMAIL ADDRESS">
       <input type="text" name="subject" class="required last" placeholder="SUBJECT">
       <textarea name="message" placeholder="YOUR MESSAGE"></textarea>
       <input type="submit" name="submit" value="SUBMIT YOUR MESSAGE">
       <h6 id="form_result">Your email will not be published.</h6>
</form>

This is the fix:

$email_to = "webmail@1tothen.com";
$header = 'From: 1totheN <webmail@1tothen.com>' . "\r\n";
$email_message .= "Name: ".clean_text($name)."\n";

I think that fixes it. I added an email to the $email_to field, and added the $name. Seems to work.


Solution

  • The below now works. It's just small syntactic mistakes, you had a few additional ; and this line is wrong and presumably a mistake: $subject = $email = $_POST['subject'];

    I also moved the function outside of the if statement...it's not incorrect to have it there, it just looks a bit weird.

    function clean_text($string) {
        $bad = array("content-type","bcc:","to:","cc:","href");
        return str_replace($bad,"",$string);
    }
    
    if(isset($_POST['email'])) {
        $email = $_POST['email'];
        $name = $_POST['name'];
        $message = $_POST['message'];
        $subject = $_POST['subject'];
    
        $email_to = $email;
        $header = 'From: 1totheN <website@1tothen.com>' . "\r\n";
        $email_message .= "Name: ".clean_text($email)."\n";
        $email_message .= "Email: ".clean_text($email)."\n";
        $email_message .= "Message: ".clean_text($message)."\n";
        @mail($email_to, $subject, $email_message, $header);
        echo "Your message has been sent.";
    }
    ?>