Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP email Form 1

Status
Not open for further replies.

TrueJoker

Technical User
Jun 14, 2006
115
GB
When creating a form that allows the user to send comments to the websmaster or any mail recipient specified within the code, is it possible to set up the form so when the email is received to have their email in the from field on the email e.g:

From: someone@somewhere.com
to: webmaster@website.com
cc:
Subject: Something!

 
yes.

if you are using the mail() command in php you add the following into the headers parameter
Code:
'From: '.$_POST['sendersemail'].'\r\n'
(obviously changing the relevant element name as needed)
 
The code i am using is as follows:

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
	"[URL unfurl="true"]http://www.w3.org/TR/REC-html40/loose.dtd">[/URL]
<html>
<head>
<title>Contact Form</title>
<meta http-equiv="Content-Type" 
   content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
   if ($_SERVER['REQUEST_METHOD'] != 'POST'){
      $me = $_SERVER['PHP_SELF'];
?>
   <form name="form1" method="post"
         action="<?php echo $me;?>">
      <table border="0" cellspacing="0" cellpadding="2">
         <tr>
            <td>Name:</td>
            <td><input type="text" name="Name"></td>
         </tr>
	 <tr>
	    <td>Email:</td>
	    <td><input type="text" name="Email"></td>
         </tr>
         <tr>
            <td>Subject</td>
            <td><input type="text" name="Subject"></td>
         </tr>
         <tr>
            <td valign="top">Message:</td>
            <td><textarea name="MsgBody"></textarea></td>
         </tr>
         <tr>
            <td>&nbsp;</td>
            <td><input type="submit" name="Submit"
               value="Send"></td>
         </tr>
      </table>
   </form>
<?php
   } else {
      error_reporting(0);
      $recipient = 'allan@cpacreative.com';
      $email = stripslashes($_POST['Email']);
      $subject = stripslashes($_POST['Subject']);
      $from = stripslashes($_POST['Name']);
      $msg = stripslashes($_POST['MsgBody']);
      if (mail($from, $email, $recipient, $subject, $msg))
         echo nl2br("<b>Message Sent:</b>
         From: $from
	 Email: $email
	 To: $recipient
         Subject: $subject
         Message: $msg");
      else
         echo "Message failed to send";
}
?>
</body>
</html>

I am still learning so this is probably very basic!
 
i don't think your mail syntax is correct.

the php manual reports that the syntax is as follows:
Code:
bool mail ( string to, string subject, string message [, string additional_headers [, string additional_parameters]] )

the "from" as i posted above, goes into the fourth parameter.
 
I know you did not ask this but one thing you really should consider for this page is protecting yourself against email injection. This is where some malicous spammer uses your contact form to send thousands of spam from your site. It happened to me and got me booted off my rented host... it also got the domain black listed. It took a lot of time and money to straighten it all out. What I learned was that if I just speant about an hour more on the contact page, it would have never happened.

There are many excellent threads on the topic in this forum, just search on "Email Injection"

Here is a really simple example function to help protect yourself. Mailing is done with PHPMailer class
Code:
   require_once "include/class.phpmailer.php";

   function protectFromEmailInjection($value) {
      $value = str_replace("\n","",$value);
      $value = str_replace("\N","",$value);
      $value = str_replace("\r","",$value);
      $value = str_replace("\R","",$value);
      return $value;
   }

   $name      = protectFromEmailInjection($HTTP_POST_VARS['name']);
   $phone     = protectFromEmailInjection($HTTP_POST_VARS['phone']);
   $email     = protectFromEmailInjection($HTTP_POST_VARS['email']);
   $comment   = protectFromEmailInjection($HTTP_POST_VARS['comment']);
   $recipient = protectFromEmailInjection($HTTP_POST_VARS['recipient']);
   $subject   = protectFromEmailInjection($HTTP_POST_VARS['subject']);
   $redirect  = $HTTP_POST_VARS['redirect'];
   $replyto   = protectFromEmailInjection($HTTP_POST_VARS['replyto']);
   $template  = $HTTP_POST_VARS['template'];

   $mail = new PHPMailer();
   $mail->From = $email; //$replyto;
   $mail->FromName = $name;
   $mail->AddAddress("request@allcost.info");
   $mail->Subject = $subject;
   $mail->Body = $comment;
   $mail->Send();

-Pete
 
good point blindpete.

a slightly neater script would be:
Code:
function cleanse($value) {
  $value = trim($value);
  if (get_magic_quotes_gpc()) $value=stripslashes($value);
  return str_replace(array('\n','\r'),'', strtotlower($value));
}
array_walk($_POST, 'cleanse');
if (mail ("allan@cpacreative.com", $_POST['Subject'], $_POST['MsgBody'], "From: ".$_POST['Email'])) {
  echo "mail sent";
else
  echo "Message failed to send";
}
 
Ive tried the code:

Code:
function cleanse($value) {
  $value = trim($value);
  if (get_magic_quotes_gpc()) $value=stripslashes($value);
  return str_replace(array('\n','\r'),', strtotlower($value));
}
array_walk($_POST, 'cleanse');
if (mail ("allan@cpacreative.com", $_POST['Subject'], $_POST['MsgBody'], "From: ".$_POST['Email'])) {
  echo "mail sent";
else
  echo "Message failed to send";
}
but when i run it, it doesnt like the 'else' at the end of the code! :-S
 
Thanx for all ya help guys! jsut a quick update i have a semi working email form now lol! but the only problem with it is that when it displays a failure to send comment etc it still sends it anyway! here is the code i am using:

Code:
<?php
/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
?>
<?php
if	((!$email =="") && (!strstr($email,"@") || !strstr($email,".")))
{
	echo "<strong>One or more fields were not filled in</strong><br>\n";
	$error = "<strong>Feedback was NOT submitted</strong>\n";
}

if	(empty($name) || empty($message) || empty($email))	{
	echo "<strong>One or more fields were not filled in. Message was not sent.</strong><br>\n";
}
	echo $error;
//Save visitor name and entered message into one variable:
$formcontent="Name: $name\n\nComment: $message";
$recipient = "me@email.com";
$subject = "$subject\r\n";
$mailheader = "From: $email\r\n";
$mailheader .= "Reply-To: $email\r\n";
$mailheader .= "MIME-Version: 1.0\r\n";
mail($recipient, $subject, $formcontent, $mailheader);
?>
 
That's becasue there is nothing telling it not to send it when there are fields missing.

You just check to see if there are missing fields but then only echo out an error, and continue to the sending part. Try adding an else statement to enclose the sending part. like so:

Code:
<?php
/*Here we are going to declare the variables*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = $_POST['subject'];
?>
<?php
if    ((!$email =="") && (!strstr($email,"@") || !strstr($email,".")))
{
    echo "<strong>One or more fields were not filled in</strong><br>\n";
    $error = "<strong>Feedback was NOT submitted</strong>\n";
}

if    (empty($name) || empty($message) || empty($email))    {
    echo "<strong>One or more fields were not filled in. Message was not sent.</strong><br>\n";
}
[red]else{[/red]
    echo $error;

//Save visitor name and entered message into one variable:
$formcontent="Name: $name\n\nComment: $message";
$recipient = "me@email.com";
$subject = "$subject\r\n";
$mailheader = "From: $email\r\n";
$mailheader .= "Reply-To: $email\r\n";
$mailheader .= "MIME-Version: 1.0\r\n";
mail($recipient, $subject, $formcontent, $mailheader);
[red]}[/red]
?>

----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top