Created
April 23, 2012 15:06
-
-
Save i-stos/2471506 to your computer and use it in GitHub Desktop.
PHP: Validate & Send simple e-mail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Validate & Send simple e-mail | |
*/ | |
function validate_field ($field) { | |
$field = htmlspecialchars($field, ENT_QUOTES); | |
if ( !empty($field) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
function validate_email($email) { | |
$email = filter_var($email, FILTER_SANITIZE_EMAIL); | |
if ( filter_var($email, FILTER_VALIDATE_EMAIL) ) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
$errors = array(); | |
if ($_SERVER['REQUEST_METHOD'] == "POST") { | |
$name = $_POST['name']; | |
$email = $_POST['email']; | |
if ( !validate_field($name) ) { | |
$errors['name'] = 'Please enter a name.'; | |
} | |
if ( !validate_email($email) ) { | |
$errors['email'] = 'Please enter a valid email.'; | |
} | |
if ( empty($errors) ) { | |
$message = $name . " requests that you contact him/her back at " . $email . "."; | |
mail("receiver@example.com", "Subject: Contact Request", $message, "From: $email"); | |
$success = "Thank you for contacting us!"; | |
} | |
} | |
?> | |
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8" > | |
<title> Some Page </title> | |
<meta name="description" content=""> | |
<meta name="author" content=""> | |
<meta name="viewport" content="width=960, initial-scale=1.0"> | |
<link rel="stylesheet" href="#" media="screen"> | |
</head> | |
<body> | |
<div id="container"> | |
<form action="index.php" method="post"> | |
<p> | |
<label for="name"> Name: </label> <br /> | |
<input type="text" name="name" placeholder="Name (required)" /> <br /> | |
<?php if ( isset($errors['name']) ): ?> | |
<?php printf("<span class='err'>" . $errors['name'] . "</span>"); ?> | |
<?php endif; ?> | |
</p> | |
<p> | |
<label for="email">Email: </label> <br /> | |
<input type="text" name="email" placeholder="Email (required)" /> <br /> | |
<?php if ( isset($errors['email']) ): ?> | |
<?php printf("<span class='err'>" . $errors['email'] . "</span>"); ?> | |
<?php endif; ?> | |
</p> | |
<p> <input type="submit" value="Contact" /> </p> | |
<?php if ( isset($success) ): ?> | |
<?php printf("<span class='success'>" . $success . "</span>"); ?> | |
<?php endif; ?> | |
</form> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment