PHP Form Email

Today we are going to learn a very interesting topic of sending a form data in an email from one email-id to another using PHP in this PHP Form Email tutorial.

  • PHP provides a very easy way to send email using a mail() function.
  • This mail() function takes 5 parameters:
    • to: this parameter is mandatory. It specifies the recipient’s email address(s).
    • subject: this parameter is mandatory. It specifies the subject of the email.
    • message: this parameter is mandatory. It specifies the actual message body. In PHP the message should not exceed 70 characters.
    • headers: this parameter is optional. It specifies additional headers like From, Content type, Cc, Bcc, etc. These headers should be separated with \r\n.
    • parameters: this parameter is optional. It specifies the additional parameters.
  • • Let us try sending a simple form data accepted by user in the email. For that we have to create a HTML form to take user input.
  • Then we will send the message using mail() function of php.
  • To demonstrate it, create a new folder named form_email in the htdocs folder in xampp folder. Open a new notepad++ document and save it as index.php in this newly created form_email folder.
  • So let us first see the code for the form for sending email:
  • <html>
    <head>
    <title>Send Form Email</title>
    <style>
    	#design{
    					border:magenta solid 5px;
    			border-radius:20px;
    			color:purple;
    			font-weight:bold;
    	}
    	h1{
    		color:purple;
    		margin-left:40px;
    		padding:10px;
    	}
    	label{
    		margin-left:50px;
    		margin-bottom:10px;
    		display:inline-block;
    		width:180px;
    	}
    	.style{
    		margin-top:20px;
    		padding:5px;
    		margin-left:190px;
    		color:purple;
    		font-weight:bold;
    		border:magenta solid 1px;
    	}
    	input{
    		border:magenta solid 1px;
    	}
    	.error{
    		color:red;
    		margin-left:10px;
    	}
    	.sent{
    		margin-left:40px;
    		padding:20px;
    		color:red;
    		font-weight:bold;
    	}
    </style>
    </head>
    <body id="design">
    <h1>Customer Contact Details</h1>
    <?php
    	if(!empty($errors))
    	{
    		foreach($errors as $err)
    			echo $err;
    	}
    ?>
    <form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
    
    <label for="name">Your Name:</label>
    <input type="text" name="name" value="<?php if(isset($_POST["name"])) echo $_POST["name"];?>"/>*<br>
    <label for="addr">Your Address:</label>
    <input type="text" name="addr" value="<?php if(isset($_POST["addr"])) echo $_POST["addr"];?>"/>*<br>
    <label for="city">City:</label>
    <input type="text" name="city" value="<?php if(isset($_POST["city"])) echo $_POST["city"];?>"/>*<br>
    <label for="state">State:</label>
    <input type="text" name="state" value="<?php if(isset($_POST["state"])) echo $_POST["state"];?>"/>*<br>
    <label for="mob">Mobile Number:</label>
    <input type="text" name="mob" value="<?php if(isset($_POST["mob"])) echo $_POST["mob"];?>"/>*
    <br>
    <label for="email">Email-ID:</label>
    <input type="text" name="email" value="<?php if(isset($_POST["email"])) echo $_POST["email"];?>">*<br>
    <input type="submit" name="send" value="SUBMIT" class="style"/>
    </form>
    </body>
    </html>
    
  • Here, we have designed a form to accept customer contact details.
  • It contains text fields to accept the name, address, city, state, mobile number and email-id of the user.
  • The value attribute of the input fields is used to retain the input entered by user.
  • Some styling is done to the fields in the form.
  • The errors in the array $errors[] are displayed in foreach loop.
  • The errors are stored in it during validation process.
  • The code for validation is written right above the HTML code. The validation code is given below:
  • <?php
    
    function clear()
    {
    	$_POST["name"]="";
    	$_POST["addr"]="";
    	$_POST["city"]="";
    	$_POST["state"]="";
    	$_POST["mob"]="";
    	$_POST["email"]="";
    }
    $satisfy=true;
    if(isset($_POST["send"]))
    {
    	$name=$_POST["name"];
    	$addr=$_POST["addr"];
    	$city=$_POST["city"];
    	$state=$_POST["state"];
    	$mob=$_POST["mob"];
    	$email=$_POST["email"];
    	
    	$errors=array();
    	
    	if(empty($name))
    	{
    		$errors[]='<p class="error">* Your name is compulsory.</p>';
    		$satisfy=false;
    	}
    	else
    	{
    		if(is_string($name))
    			$satisfy=true;
    		else
    		{
    			$errors[]='<p class="error">* Name should be in string format.</p>';
    			$satisfy=false;
    		}
    	}
    	
    	if(empty($addr))
    	{
    		$errors[]='<p class="error">* Address cannot be blank.</p>';
    		$satisfy=false;
    	}
    	
    	if(empty($city))
    	{
    		$errors[]='<p class="error">* City is compulsory.</p>';
    		$satisfy=false;
    	}
    	else
    	{
    		if(is_string($city))
    			$satisfy=true;
    		else
    		{
    			$errors[]='<p class="error">* City should be in string format.</p>';
    			$satisfy=false;
    		}
    	}
    	
    	if(empty($state))
    	{
    		$errors[]='<p class="error">* State is compulsory.</p>';
    		$satisfy=false;
    	}
    	else
    	{
    		if(is_string($state))
    			$satisfy=true;
    		else
    		{
    			$errors[]='<p class="error">* State should be in string format.</p>';
    			$satisfy=false;
    		}
    	}
    	
    	if(empty($mob))
    	{
    		$errors[]='<p class="error">* Mobile number is compulsory.</p>';
    		$satisfy=false;
    	}
    	else
    	{
    		if(strlen($mob)==10 && is_numeric($mob))
    			$satisfy=true;
    		else
    		{
    			$errors[]='<p class="error">* Mobile number should contain a 10 digit number.</p>';
    		}
    	}
    	
    	if(empty($email))
    	{
    		$errors[]='<p class="error">* Email-id is compulsory.</p>';
    		$satisfy=false;
    	}
    	else
    	{
    		if(!preg_match('/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/',$email))
    		{
    			$errors[]='<p class="error">* Email-id is not in proper format.</p>';
    			$satisfy=false;
    		}
    	}
    	
    	if($satisfy==true)
    	{
    		//mail details
    		$mail_to="[email protected]";
    		$mail_from=$email;
    		$mail_sub="Contact details of the customer";
    		
    		$mail_msg="Details of the customer who purchased a Google Android One handset is as follows:\n\n";
    		$mail_msg.="Name: ".$name."  Address: ".$addr."  City: ".$city."  State: ".$state."  Mobile Number: ".$mob."  Email-ID: ".$email."\n\n";
    		
    		$mail_msg=wordwrap($mail_msg,70);
    		
    		$mail_header="From: ".$mail_from."\r\n";
    		$mail_header.="Reply-to:".$mail_from."\r\n";
    		//mail function
    		mail($mail_to,$mail_sub,$mail_msg,$mail_header);
    		echo '<p class="sent">** Your message has been sent successfully!</p>';
    		clear();
    	}
    
    }
    ?>
    
  • The above code is used to validate the form and send its contents in the email.
  • We have declared a variable $satisfy which is initialized to true initially.
  • When anything is not validated, $satisfy will be set to false telling us that our form is not yet validated. But if its value remains true, it means our form is completely validated.
  • Next it is checked that whether the SUBMIT button has been clicked and if it is clicked, the values stored in the $_POST superglobal array variable are retrieved and stored in the local variables.
  • The empty $errors array is declared to store the errors if any.
  • The $name variable containing the name of the customer, the $addr variable containing the customer’s residential address, $city, $state, $mob and $email are checked to see if they are empty.
  • If they are empty, the error messages are stored in the array $errors and $satisfy variable is set to false.
  • The $name, $city, $state variables is also checked to see if they contain string format using is_string() function.
  • The $mob variable is checked to see if it contains only numbers and has only 10 digits.
  • The $email variable is checked using preg_match() function to see if it is in proper format or not. This function matches the email-id entered by user with the regular expression for email-id.
  • If the match fails an error message is stored in the $errors array and $satisfy variable is set to false.
  • Next if the $satisfy valriable is checked to see its value is true.
  • If its value is not true, the error messages are displayed in the form using the foreach loop as shown in the code for HTML form.
  • And if the value of $satisfy is true, it means the form is completely validated.
  • After confirming the validation of the form mail details are gathered and the function mail() is used to send the email as shown below:
  • if($satisfy==true)
    	{
    		//mail details
    		$mail_to="[email protected]";
    		$mail_from=$email;
    		$mail_sub="Contact details of the customer";
    		
    		$mail_msg="Details of the customer who purchased a Google Android One handset is as follows:\n\n";
    		$mail_msg.="Name: ".$name."  Address: ".$addr."  City: ".$city."  State: ".$state."  Mobile Number: ".$mob."  Email-ID: ".$email."\n\n";
    		
    		$mail_msg=wordwrap($mail_msg,70);
    		
    		$mail_header="From: ".$mail_from."\r\n";
    		$mail_header.="Reply-to:".$mail_from."\r\n";
    		//mail function
    		mail($mail_to,$mail_sub,$mail_msg,$mail_header);
    		echo '<p class="sent">** Your message has been sent successfully!</p>';
    		clear();
    	}
    
  • So here if $satisfy has value true, the mail details such as email-id of the recipient, email-id of the sender, subject of the email , the message and the message header are made ready.
  • Here the email-id of the recipient is fixed i.e. [email protected].
  • Next the email-id of the sender is taken from the form which is stored in $email variable.
  • Subject is also fixed i.e. Contact details of customer.
  • All the details entered by user are included in the $mail_msg variable as shown below:
  • $mail_msg="Details of the customer who purchased a Google Android One handset is as follows:\n\n";
    $mail_msg.="Name: ".$name."  Address: ".$addr."  City: ".$city."  State: ".$state."  Mobile Number: ".$mob."  Email-ID: ".$email."\n\n";
    
  • The statements end with \n\n, it gives a new line. The user input is concatenated to the above statement using string concatenation operator (.=).
  • The message should not exceed 70 characters. This is achieved using the wordwrap() function as shown below:
  • $mail_msg=wordwrap($_POST["msg"],70);
  • The wordwrap() function wraps the text. It takes 2 parameters, first is the message to be wrapped and the second is the number of characters.
  • A $mail_header variable is initialized with the headers like From and Reply-to.
  • The code is shown below:
  • $mail_header="From: ".$mail_from."\r\n";
    $mail_header.="Reply-to:".$mail_from."\r\n";
  • In the code the email–id of the sender is concatenated with the From header.
  • The From header is again concatenated with Reply-to header with email-id of sender as its value.
  • Both the statements are terminated with “\r\n”, because the rule is that each header should terminate with \r\n.
  • The mail function is then called with parameters $mail_to, $mail_sub, $mail_msg and $mail_header.
  • Then after execution of mail() function a statement “Your message has been sent successfully!” is displayed.
  • Then a clear() function is called which clears the text fields of all the fields.
  • The clear() function is shown below:
  • function clear()
    {
    	$_POST["name"]="";
    	$_POST["addr"]="";
    	$_POST["city"]="";
    	$_POST["state"]="";
    	$_POST["mob"]="";
    	$_POST["email"]="";
    }
    
  • Here the values of name, addr, city, state, mob and email fields are replaced with empty string so that after sending the message, the values of the fields are not displayed in the text fields again.
  • The output of the compose form is shown below:
  • form
    fig 1

  • Now let us click the SUBMIT button without entering the information. We will get all the errors as shown below:
  • all_errors_output
    fig 2

  • • Now let us enter the information in the form. I will keep some fields blank and will enter wrong input in some fields and then click on SUBMIT button. The output is as shown below:
  • incomplete_form
    fig 3

  • Now let us correct our mistake and complete the whole form as shown below:
  • complete_form
    fig 4

  • Now click on the SUBMIT button. The output is shown below:
  • mail_sent_output
    fig 5

  • • Thus our form data has been sent in the email

Thus we studied how to send a form data in the email using PHP in this PHP Form Email tutorial.

Previous articlePHP Sessions
Next articleNamespaces in PHP

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -