saftutorials.com
PHP Contact Form

In the contact form when users fill the all required field and click on submit button, then below script executes and send the email to the mention mail id.

Complete Contact Form Example is given below

<!DOCTYPE html>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $queryErr = $mobileErr = "";
$name = $email = $query = $mobile = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
 $nameErr = "Name is required";
}else {
 $name = validate_input($_POST["name"]);
}
if (empty($_POST["email"])) {
 $emailErr = "Email is required";
}else {
 $email = validate_input($_POST["email"]);
 // check if email address is invalid
 if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $emailErr = "Invalid email format"; 
 }
}
if (empty($_POST["mobile"])) {
 $mobileErr = "Mobile is required";
}
else {
 $mobile = validate_input($_POST["mobile"]);
// check if email address is valid
 if (!filter_var($mobile, FILTER_VALIDATE_INT)) {
    $mobileErr = "Invalid mobile no"; 
 }
}
if (empty($_POST["query"])) {
 $queryErr = "Query is required";
}else {
 $query = validate_input($_POST["query"]);
}
if(!$nameErr && !$emailErr && !$mobileErr && !$queryErr){
$subject = 'Contact from mail';
$msg = 'Name: '.$name.'<br />Email: '.$email.'<br />Mobile: '.$mobile.'<br />Query: '.$query;
$result = mail("admin@example.com","My subject",$msg);
if($result)
$message = 'Request submitted';
}
}
function validate_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Contact Form</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
 <td>Name:</td>
 <td><input type="text" name="name"><span class="error">* <?php echo $nameErr;?></span></td>
</tr>
<tr>
 <td>Email Id: </td>
 <td><input type="text" name="email"><span class="error">* <?php echo $emailErr;?></span></td>
</tr>
<tr>
 <td>Mobile:</td>
 <td><input type="text" name="mobile"><span class="error"><?php echo $mobileErr;?></span></td>
</tr>
<tr>
 <td>Query:</td>
 <td> <textarea name ="query" rows = "5" cols = "40"></textarea><span class="error"><?php echo $mobileErr;?></span></td>
</tr>
<tr>
 <td><span style="color:green;"><?php echo $message;?></span></td>
</tr>
<tr><td><input type="submit" name="submit" value="Submit"></td></tr>
</table>
</form>
</body>
</html>


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic