Emailing Form Contents Using PHP

This page is a demo of how to email contents of a form using PHP. Create a file called form.php like below:

<?php 
      if (isset($HTTP_POST_VARS) && ereg("@", $to)
	  && ereg("@", $from) && ($redirect != "")) {

            // Add all the POSTed variables to the message body
            while (list($key, $value) = each($HTTP_POST_VARS)){ 
                $body .= $key . ' = ' . $value . "\r\n"; 
            } 

            // Requires setting sendmail (unix) in the path
	    $headers  = "From: ".$from."\n";
            $success = mail($to, "Posted " . date("m/d/Y"), $body, $headers); 

            if ($success) { 
		header ("Location:  $redirect");
            } else { 
	        die ("Internal Error: Couldn't send out mail!\n");
	    }
      } else {
	    die ("Error: Unrecognized input!  Contact webmaster.\n");
      }
?>

In your HTML file, use something like below (note that this is just a barebones form as seen above; you would replace the TEXTAREA tag with your usual form fields and use the accurate URL_PATH for the script):

<FORM METHOD=POST ACTION="http://URL_PATH/form.php">
<TEXTAREA NAME=mesg COLS=30 ROWS=4 WRAP=virtual>
<INPUT TYPE=submit VALUE="Send Us The Message">
<INPUT TYPE=hidden NAME="to" VALUE="techy@charityfocus.org">
<INPUT TYPE=hidden NAME="from" VALUE="autoemail@domain.com">
<INPUT TYPE=hidden NAME="redirect" VALUE="http://charityfocus.org/">
</FORM>

Please also remember that you use your own copy of the script; the existing one on cf1.org should not be used elsewhere is likely to be modified anytime! For more examples and/or other ideas, check out zend.com.

Also note that you can also just use the mailto tag (although not as flexible as above option):

<FORM METHOD=POST NAME="subscribeme"
      ACTION="mailto:nipun@charityfocus.org">
<textarea name=mesg cols=30 rows=4 wrap=virtual>
</FORM>

If you have any questions, please feel free to email tech@charityfocus.org.