Trying to Learn Javascript Trying to Learn Javascript - 7 months ago 13
PHP Question

PHP Email Validation and Retrieval from an HTML form

I've been trying to create a form that will gather a user's Name, Email and Question, but I'm so new to PHP that I've been really struggling with it.

The goal is to collect the information, and when they press submit, their email address is supposed to be sent to my email and I'd like it to be validated that it's a real email address.

HTML Code:

<form method="post" action="process.php">
<fieldset>
<legend>Personal Information</legend>


<p><label for="name">Name:</label>
<input type="text" name="name" id="name" maxlength="50" autofocus required /></p>

<p><label for="recipient">Email Address:</label>
<input id="recipient" name="recipient" type="text" name="recipient" required></p>


</fieldset>

<fieldset>
<legend>Tours Interested In:</legend>

<p><label for="question">Questions/Comments:</label>
<textarea id="question" name="question" cols="50" rows="3" placeholder="type your comments here" required></textarea>
</fieldset>

<p class="centralize"><input type="submit" onclick="send()" value="Submit Only" /></p>
<p class="centralize"><input type="reset" value="Clear Form"></p>

<p id="data_return"></p>


</form>


PHP CODE:

<?php
header("Content-type: text/html");

$name=$_POST["name"];
$question=$_POST["question"];
$email =$_POST["email"];

$subject = "You have a USER INQUIRY:";
$to = 'myemail@myemail.com';


if(!$_POST['name']){
$errName = 'Please enter your name';
}






echo "<p>Thank you, $name . Your Email has been Sent, and we will get back to you within 48 hours.</p>";

//Build email (to myself)


mail($to, $name, $subject, $question, $email);

Answer

Check how mail() function works in php here. And check this code below. Good luck :)

<?php
header("Content-type: text/html");
if(isset($_POST['submit'])){ //check if the submit button actually clicked
  $name=$_POST["name"];
  $question=$_POST["question"];
  $email = test_input($_POST["recipient"]);
  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {  //php validations http://www.w3schools.com/php/php_form_url_email.asp
    echo "Invalid email format";
  }

  $subject = "You have a USER INQUIRY:";
  $to = 'myemail@myemail.com';
  $message = "Name: {$name} \n";
  $message .= "Email: {$email} \n"; 
  $message .= "Question: {$question} \n";


  if(!$_POST['name']){
    $errName = 'Please enter your name';
  }

   echo "<p>Thank you," . $name . "Your Email has been Sent, and we will get     back to you within 48 hours.</p>";

   //Build email (to myself)

   mail($to, $subject, $message);
}

And also in your html you can say input type=email which is supported by many browsers.

<input id="recipient" name="recipient" type="email" required></p>