treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Adding a variable to existing mail script help

  • Hi all,
    I have this piece of code:

    <?php
    error_reporting(E_NOTICE);

    function valid_email($str)
    {
    return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
    }

    if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
    {
    $to = "damian.herrington@yahoo.co.uk";
    $headers = 'From: '.$_POST['email'].''. "\r\n" .
    'Reply-To: '.$_POST['email'].'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    $subject = "Contact Form";
    $message = htmlspecialchars($_POST['comment']);

    if(mail($to, $subject, $message, $headers))
    {
    echo 1; //SUCCESS
    }
    else {
    echo 2; //FAILURE - server failure
    }
    }
    else {
    echo 3; //FAILURE - not valid email
    }
    ?>

    As you can see it takes the information entered from the form and stores it before sending to my email address. But I have a form input called name, how would I add that variable, $_POST['name'] into $message either the persons name then the comment or vice versa?
    Thanks
  • You could modify the message variable like this:

    $message = htmlspecialchars($_POST['comment']) . "\r\nName: " . htmlspecialchars($_POST['name']);

    The "." adds on to the string, and the "\r\nName: " section adds a new line and then the text "Name:" before the person's name, just so your email is easy to understand.

    Make sense?
  • Thanks for the quick reply I will try that out later :-)