Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Contact Form with PHP
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
$name = '';
$email = '';
$subject = '';
$message = '';
$err_msg = '';
$complete_msg = '';
} else {
// Get input values.
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$err_msg = '';
$complete_msg = '';
// Empty check.
if ($name == '' || $email == '' || $subject == '' || $message == '') {
$err_msg = 'Please fill in all fields.';
}
if ($err_msg == '') {
// Send email.
$to = 'codingwithsara@gmail.com'; // Set your email!!
$headers = 'From: ' . $email . '\r\n';
mail($to, $subject, $message, $headers);
$complete_msg = 'Your message was sent successfully!';
// Clear all fields.
$name = '';
$email = '';
$subject = '';
$message = '';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contact Form</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<style>
body {
background: #f3f3f3;
}
.container {
font-family: 'Montserrat', sans-serif;
margin-top: 50px;
}
h1 {
margin-bottom: 50px;
text-align: center;
}
button {
margin-top: 30px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-xs-offset-4 col-xs-4">
<h1>Contact Form</h1>
<?php if ($err_msg != ''): ?>
<div class="alert alert-danger">
<?php echo $err_msg; ?>
</div>
<?php endif; ?>
<?php if ($complete_msg != ''): ?>
<div class="alert alert-success">
<?php echo $complete_msg; ?>
</div>
<?php endif; ?>
<form method="post">
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Name" value="<?php echo $name; ?>">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email" value="<?php echo $email; ?>">
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" placeholder="Subject" value="<?php echo $subject; ?>">
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" placeholder="Message"><?php echo $message; ?></textarea>
</div>
<button type="submit" class="btn btn-success btn-block">Send</button>
</form>
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment