Jump to content

Making the Senders Name appear in the from area of an e-mail.


iconicCreator

Recommended Posts

Good day,

 

I searched the forum but cannot find a related post.

 

I created this script, however, I can't seem to figure out how to get the senders name in the From area.

Example: From: John Doe, which is the senders first and last name as entered on the form.

 

I have tried adding that to the header but it does not work.

 

Please Note: The script below is a working version.

 

Here is my mail script:

 

<?php
session_start();
$_SESSION = array();
$post = array("firstName" => "","lastName" => "","email" => "","phoneNumber" => "","comment" => "","subscribe" => "");

$errors = $post;
if (isset($_POST["submitBtn"]))
{

foreach ($post as $k => $v)
$post[$k] = stripslashes($_POST[$k]);

//VALIDATE FIRST NAME
if (empty($post["firstName"]))
$errors["firstName"] = "*Required";
else 
{
if (!preg_match('([a-zA-Z])', $post['firstName']))
$errors["firstName"] = "*Invalid";
}

//VALIDATE LAST NAME
if (empty($post["lastName"]))
$errors["lastName"] = "*Required";
else 
{
if (!preg_match('([a-zA-Z])', $post['lastName']))
$errors["lastName"] = "*Invalid Name";
}

    //VALIDATE EMAIL
if (empty($post["email"]))
$errors["email"] = "*Required";
else
{
if (!preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $post["email"]))
$errors["email"] = "*Invalid Email";
}

//VALIDATE PHONE NUMBER
if (empty($post["phoneNumber"]))
$errors["phoneNumber"] = "*Required";
else
{
if (!preg_match('/^[0-9]{3}-[0-9]{3}-[0-9]{4}$/', $post["phoneNumber"]))
{
$errors["phoneNumber"] = "*Invalid";
}
}

//VALIDATE MESSAGE OR COMMENTS
if (empty($post["comment"]))
    $errors["comment"] = "*Required";

$error = false;
foreach($errors as $k => $v)
{
if ($errors[$k] != "")
$error = true;
}

if (!$error)
{
$address = "example@example.com";
$subject = "Example";

$message = "You have recieved new information via your website form. The details entered are as follows:<br><br>";
$message .= "<b>First Name:</b> ".$post['firstName']."<br>";
$message .= "<b>Last Name:</b> ".$post['lastName']."<br>";
$message .= "<b>Email:</b> ".$post['email']."<br>";
$message .= "<b>Phone Number:</b> ".$post['phoneNumber']."<br><br>";
$message .= "<b>Comments/Message:</b> ".$post['comment']."<br><br>";
$message .= "<b>Subcribed:</b> ".$post['subscribe']."<br><br>";

$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: '.$post['firstName']." ".$post['lastName'].'<example@example.com>' . "\r\n";

mail($address, $subject, $message, $headers);
  $_SESSION['firstName'] = $firstName;
     header('Location: message-confirm.php');
   exit;
}
}
?>

 

 

Thanks!

 

IC

Link to comment
Share on other sites

Did you validate the values you are passing into the mail() function? Specifically the $headers vaeriable? Echo it to the page to ensure it contains the values for first .name and last name that you expect.

 

Fior some reason you decided to create an array called $post to store your $_POST values. This is confusin since it really isn't POST values. But, anyway you first define all the keys (including first and last name) as empty values and then populate it with values from $_POST. But, since we can't see the contents of $_POST we can't know if there are values under the indexes of "firstName"  and "lastName". Could be that you have a mismatch between the key names and you are workign with empty strings. So, echo the different variables used in the mail() function to the page to validate their values. This is debugging 101.

 

The one thing that *may* be a problem is you don't have a space between the last name and the "<". Don't know if that is acceptable or not.

Link to comment
Share on other sites

Did you validate the values you are passing into the mail() function? Specifically the $headers vaeriable? Echo it to the page to ensure it contains the values for first .name and last name that you expect.

 

Fior some reason you decided to create an array called $post to store your $_POST values. This is confusin since it really isn't POST values. But, anyway you first define all the keys (including first and last name) as empty values and then populate it with values from $_POST. But, since we can't see the contents of $_POST we can't know if there are values under the indexes of "firstName"  and "lastName". Could be that you have a mismatch between the key names and you are workign with empty strings. So, echo the different variables used in the mail() function to the page to validate their values. This is debugging 101.

 

The one thing that *may* be a problem is you don't have a space between the last name and the "<". Don't know if that is acceptable or not.

 

I can change the name is the array but I am not sure that will solve the problem. I agree that is confusing. However, I am getting values under the indexes, what I mean is all the form fields are populating I am getting the values printed to the page.

 

When I get an e-mail, it simply says the e-mail is from my e-mail address rather then the senders name.

 

Thanks for your input.

 

IC

 

Link to comment
Share on other sites

I can change the name is the array but I am not sure that will solve the problem. I agree that is confusing. However, I am getting values under the indexes, what I mean is all the form fields are populating I am getting the values printed to the page.

 

When I get an e-mail, it simply says the e-mail is from my e-mail address rather then the senders name.

 

So, you are saying you didn't take the 30 seconds to perform the one debugging step I proposed? Did you echo "$headers" to the page to validate it has the information you expect?

Link to comment
Share on other sites

I can change the name is the array but I am not sure that will solve the problem. I agree that is confusing. However, I am getting values under the indexes, what I mean is all the form fields are populating I am getting the values printed to the page.

 

When I get an e-mail, it simply says the e-mail is from my e-mail address rather then the senders name.

 

So, you are saying you didn't take the 30 seconds to perform the one debugging step I proposed? Did you echo "$headers" to the page to validate it has the information you expect?

 

Hi, just got around to doing that, I was not around a test environment.

Also I am not sure I am doing this right but when I try to echo the header, I get the following error message.

 

Notice: Undefined variable: headers in C:\active-projects\driven-factor\test-form.php on line 88

 

In a nutshell the header is not define.

 

Basically what I did was manually fed the variables by assigning them values rather then through the form fields.

 

Are we on the same page?

 

IC

Link to comment
Share on other sites

Basically what I did was manually fed the variables by assigning them values rather then through the form fields.

 

Are we on the same page?

 

No we are not. Manually setting the values defeats the purpose of verifying that the values are getting properly set!

 

All you need to do is add an

echo $headers;

after you define that variable.

 

I went ahead and implemented a debug mode for the script above. But, there were other issues, so I went ahead and addressed those as well. Also, some of you validations are problematic. For example, for the name fields you only allow "a-z". But what the user has a name such as "De la Hoya" or "D'Angelo"? I didn't change those, but you need to reconsider what you are doing. But, the way you are using preg_match(0 is incorrect as well. You are testing if it is returning false (or 0). But, the pattern is only checking to see if ANY letter is in the string. So event the value "#%^&%^$-A-^&^&*#$" would pass the validation. I did fix that by changing the pattern to look for any character that is NOT a-z.

 

I made a lot of changes, so there may be some syntax errors - I didn't test. Set the $debug variable to false to have the code work normally - i.e. send the email. Or, set it to true and it will print debug info to the page

<?php

$debug = true;

session_start();
$_SESSION = array();

function cleanPost($value)
{
    if (get_magic_quotes_gpc())
    {
        $value = stripslashes($value);
    }
    return(trim($value));
}

$errors = array();
if (isset($_POST["submitBtn"]))
{
    //Parse POST values
$firstName   = cleanPost($_POST['firstName']);
    $lastName    = cleanPost($_POST['lastName']);
    $email       = cleanPost($_POST['email']);
    $phoneNumber = cleanPost($_POST['phoneNumber']);
    $comment     = cleanPost($_POST['comment']);
    $subscribe   = cleanPost($_POST['subscribe']);

//VALIDATE FIRST NAME
if (empty($firstName))
    {
        $errors[] = "First name is required";
    }
elseif (preg_match('#[^a-zA-Z]#', $firstName)>0)
    {
        $errors[] = "First name is invalid";
}

//VALIDATE LAST NAME
if (empty($lastName))
    {
    	$errors[] = "Last name is required";
    }
elseif (preg_match('#[^a-zA-Z]#', $lastName)>0)
    {
        $errors[] = "Last name is invalid";
}

    //VALIDATE EMAIL
if (empty($email))
    {
    	$errors[] = "Email is required";
    }
elseif (!preg_match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^", $email))
    {
        $errors[] = "Email is invalid";
}

//VALIDATE PHONE NUMBER
if (empty($phoneNumber))
    {
    	$errors[] = "Phone Number is required";
    }
else
    {
        $digits = preg_replace('/[^\d]/', '', $phoneNumber);
        if(strlen($digits)!=10)
        {
            $errors[] = "Phone number is invalid";
        }
        else
        {
            $phoneNumber = substr($digits, 0, 3).'-'.substr($digits, 3, 3).'-'.substr($digits, 6);
        }
}

//VALIDATE MESSAGE OR COMMENTS
if (empty($comment))
    {
        $errors[] = "Comment is required";
    }

if (count($errors)==0)
{
        //No errors, prepare and send the email
        $address = "example@example.com";
        $subject = "Example";
        
        $message = "You have recieved new information via your website form. The details entered are as follows:<br><br>";
        $message .= "<b>First Name:</b> ".$post['firstName']."<br>";
        $message .= "<b>Last Name:</b> ".$post['lastName']."<br>";
        $message .= "<b>Email:</b> ".$post['email']."<br>";
        $message .= "<b>Phone Number:</b> ".$post['phoneNumber']."<br><br>";
        $message .= "<b>Comments/Message:</b> ".$post['comment']."<br><br>";
        $message .= "<b>Subcribed:</b> ".$post['subscribe']."<br><br>";
        
        $headers  = 'MIME-Version: 1.0' . "\r\n";
        $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
        $headers .= 'From: '.$post['firstName']." ".$post['lastName'].'<example@example.com>' . "\r\n";
        
        if($debug != true)
        {
            //Send the email
            $sent = mail($address, $subject, $message, $headers);
            if(!$sent)
            {
                echo "There was a problem sending the email";
            }
            else
            {
                $_SESSION['firstName'] = $firstName;
                header('Location: message-confirm.php');
                exit;
            }
        }
        else
        {
            //Display the variable values
            echo "<b>Debug Info:<b><br>\n";
            echo "Address: " . htmlentities($address) . "\n\n";
            echo "Subject: " . htmlentities($subject) . "\n\n";
            echo "Message: " . htmlentities($message) . "\n\n";
            echo "Headers: " . htmlentities($headers) . "\n\n";
        }
}
    else
    {
        //Display the errors
        echo "The following errors occured:<br>\n";
        echo "<ul>\n";
        foreach($errors as $error)
        {
            "<li>{$error}</li>\n";
        }
        echo "/<ul>\n";
    }
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.