Wednesday, August 1, 2018

Contact us form in php

Contact us form in php

In this post we will learn below functionality :

1. HTML UI of contact us page.
2. HTML validations.
3. Manage CSS.
4. Email all details on our email id.

1. HTML UI of contact us page: Here is the example of basic HTML form for contact us page.


   
      <h2>Contact Form</h2>
<form id="form" method="post" action="contact_us.php">
    <fieldset>
      <label><input name="name" id="name" placeholder="Name*" required type="text"></label>
      <label><input name="email" id="email" required type="email" placeholder="Email*"></label>
      <label><input name="phone_no" required type="text" placeholder="Phone*"></label>
      <label><textarea name="query" required placeholder="Message*"></textarea></label>
      <div class="btns">
        <input class="send-btn" type="submit" value="Send" name="">
      </div>
    </fieldset>  
</form>
   
 

Here,
method="post" (To post data on the server by POST method)
action="contact_us.php" (Form data will post on contact_us.php page)




2. HTML validations : Below are the HTML 5 validations which we used in HTML form  
required (This is the required validation of HTML 5)
required type="email" (This is for required with valid email address)


3. Manage CSS: Use below CSS to style your submit button 

.send-btn{
width:100%;
height:30px;
margin-bottom:10px;
background-color: #ff9000;
color: #fff;
border-radius: 10px;
}

4. Email all details on our email id: Create a contact_us.php file and add below code in this file 


$tryAgainUrl="<a href='contacts.html'>Try Again</a>";
if(!empty($_POST))
{
if( $_POST['name'] && $_POST['query'] && $_POST['phone_no'] && $_POST['email'])
{
$name=$_POST['name'];
$query=$_POST['query'];
$phone_no=$_POST['phone_no'];

/* email send code start */
$from="info@yourdomain.com";
$to="support@yourdomain.com";
$email=$_POST['email'];
$subject = 'Contact us query';
$message ="Name : ".$name."\r\n\r\n";
$message.="Email : ".$email."\r\n\r\n";
$message.="Phone No :- ".$phone_no."\r\n\r\n";
$message.="Message :- ".$query."\r\n\r\n";

$headers = "From: $from\r\nReply-to: $email";
$sent = mail($to, $subject, $message, $headers);
/* email send code end */

header("Location: contacts.html"); /* Redirect browser */
exit();
}else{
echo "Invalid Details. ".$tryAgainUrl;
}
}else{
echo "Invalid Details. ".$tryAgainUrl;
}
?>


Here :
mail(to,subject,message,headers);

$to = This is required. (Receiver email address)
$subject = This is required. (Subject of the email)
$message = This is required. (Defines the message to be sent) 
$headers = This is Optional. (Specifies additional headers, like From, Cc, and Bcc)








1 comment:

  1. This code is vulnerable to header injection attacks. That's a pretty big oversight.

    ReplyDelete