Looking to send input from a form to my email

I’m new to php and I’ve now built 2 forms and can’t seem to get it right. I just need a couple boxes for email name number. I need it to send to my business email. That’s all. the tutorials i’ve found are vague or not working.

It is a good idea to post your code so we can see what you have already. Do not forget you will need some user input validation to try and prevent people hacking your site and misusing your forms.

1 Like

Here is my code. But instead of posting to the page. I want to send the input to my email.

<!DOCTYPE HTML>  
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>  

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
    // check if name only contains letters and whitespace
    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $nameErr = "Only letters and white space allowed"; 
    }
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
    }
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
    // check if URL address syntax is valid (this regular expression also allows dashes in the URL)
    if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
      $websiteErr = "Invalid URL"; 
    }
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">  
  Name: <input type="text" name="name" value="<?php echo $name;?>">
  <span class="error">* <?php echo $nameErr;?></span>
  <br><br>
  E-mail: <input type="text" name="email" value="<?php echo $email;?>">
  <span class="error">* <?php echo $emailErr;?></span>
  <br><br>
  Website: <input type="text" name="website" value="<?php echo $website;?>">
  <span class="error"><?php echo $websiteErr;?></span>
  <br><br>
  Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
  <br><br>
  Gender:
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
  <input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
  <span class="error">* <?php echo $genderErr;?></span>
  <br><br>
  <input type="submit" name="submit" value="Submit">  
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
?>

</body>
</html>

I would set a common error variable for all of the variables which you can use to decide to send the email or not.
e.g

if (empty($_POST["email"])) {
    $emailErr = "Email is required";
    $stop = '1';
  } else {
    $email = test_input($_POST["email"]);
    // check if e-mail address is well-formed
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid email format"; 
      $stop = '1';
    }
else
{
$stop = '0';
}
  }

If you do that for all of the fields then after the checks if $stop >0 then you know an error has occurred and you don’t run the send or if there are no validation errors do the send. A lot of people don’t like mail() function but i rarely have a problem with it so i would use it.
look here for an example of how to set it up https://www.w3schools.com/php/func_mail_mail.asp

First of all correct some errors in code

// invalid
if ($SERVER["REQUESTMETHOD"] == "POST") {
// valid
if ($_SERVER["REQUEST_METHOD"] == "POST") {

// invalid
action="<?php echo htmlspecialchars($<em>SERVER["PHPSELF"]);?>"
// valid
action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"

And instead of using $emailErr = "Email is required"; you can put in input field required="required" to avoid checking in code.

When you post code on the forums, you need to format it so it will display correctly. You can highlight your code, then use the </> button in the editor window, or you can place three backticks ``` (top left key on US/UK keyboards) on a line above your code, and three on a line below your code. I find this approach easier, but unfortunately some European and other keyboards don’t have that character.

Do you mean in the form field html? I would do that but i would also leave the server side validation. Anything client side can be got around

1 Like

Yes you can put it like this only on required fields, this way user press button and it will ask for him to fill it.

<input type="text" name="name" required="required">
<input type="email" name="email" required="required">
<input type="radio" name="gender" value="female" required="required">Female
<input type="radio" name="gender" value="male" required="required">Male

Having the required attribute doesn’t excuse the fact people can change those elements on their own browser.

Number 1 rule of web security: Never trust user input.

3 Likes

know of any good tutorials on building such a form? I’d like to better understand it

Would you happen to know of any solid tutorials on building a php contact form from scratch. The ones that I have found are very vague and more often then not end up not working

I do not recommend “learning” from any kind of tutorial. The best 'tutorial" is learning from the PHP documents. It’s ok to learn bits of code from random places. But copying&pasting a whole section from a “tutorial” isn’t “learning”.

It’s easier if you break it down into sections. I tend to build the form and the sending part all on one page but you could also do it with multiple pages each doing part of the process. I’ll outline how i’d do it all on one page.

check if form submitted -> form not submitted so show form -> form filled and submitted -> page reloads and checks the form is submitted -> validate variables -> if good send email - > display success message on page.

This assumes there are no validation problems. If there are we will want to kick the user back to the form and show which bit is wrong.

My page has the check for submission, sending code and success message at the top and the form below. The form is turned off or on by checking a variable that is set in the validation process as in previous post.

Hope that makes sense and is useful.

You don’t have to scroll very far down this forum to see various bits of sample code for sending emails based on form input. Some of them may give some ideas that would be helpful.

Generally I’d agree with @noppy that it’s just like any other programming task, break it down into steps and code each one.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.