GENWiki

Premier IT Outsourcing and Support Services within the UK

User Tools

Site Tools


php:a_simple_web_form_to_email

Using PHP to Send an Email from a HTML Form

<?php 
if(isset($_POST['submit'])){
 
// When the form submits, PHP puts the submission variables in $_POST so we can access them simply by $_POST["name"] where name is the name of the variable. 
// We will check to see if there's a variable named "submit" in $_POST since if it exists the form has posted, if not we do nothing. 
 
    $email = $_POST['email']; // email address from the form
    $forename = $_POST['forename']; // forename from the form
    $surname = $_POST['surname']; // surname from the form
    $message=$_POST['message']; // message from the form. 
 
    $headers = "From: webserver@mydomain.com"; // we need to set the from address here and it needs to be valid or our mail server will reject it.
 
    mail($email,"Website Form",$message,$headers); 
    // send the email to $email with subject "test" the body is $message and the headers (from) is $headers
 
    echo "Mail Sent. Thank you ".$forename.", we will contact you shortly."; // Drop a thank you message to the browser.
 
    }
?>
<!DOCTYPE html>
<html>
 <head>
 <title>Form submission</title>
 </head>
 <body>
  <form action="" method="post"><!-- This is the start of the form -->
   First Name: <input type="text" name="forename"><br>
   Last Name: <input type="text" name="surname"><br>
   Email: <input type="text" name="email"><br>
   Message:<br><textarea rows="5" name="message" cols="30"></textarea><br>
   <input type="submit" name="submit" value="Submit"><!-- This line creates a button which submits the form -->
  </form><!-- The end of the form -->
 </body>
</html>

Essentially this code is a simple HTML Form with zero elegance but a great example. It posts to itself, wherein the PHP code looks for that post (Remember PHP provides a form post in $_POST) and then sends the message via email.

You can hack this around all you wish, its public domain code.

/home/gen.uk/domains/wiki.gen.uk/public_html/data/pages/php/a_simple_web_form_to_email.txt · Last modified: 2023/01/13 15:46 by genadmin

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki