PHP contact form, am I doing it wrong?
Posted
by decimal
on Stack Overflow
See other posts from Stack Overflow
or by decimal
Published on 2010-05-13T12:57:42Z
Indexed on
2010/05/13
13:24 UTC
Read the original article
Hit count: 191
I'm learning PHP and I'm trying to write a simple email script. I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). I'm not sure how to return true checkEmpty funciton. Here's my code:
When the submit button is clicked:
if (isset($_POST['submit'])) {
//INSERT FORM VALUES INTO AN ARRAY
$field = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' => $_POST['message']);
//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($field);
checkEmpty($name, $email, $message);
function checkEmpty($name, $email, $message) {
global $name_error;
global $mail_error;
global $message_error;
//CHECK IF NAME FIELD IS EMPTY
if (isset($name) === true && empty($name) === true) {
$name_error = "<span class='error_text'>* Please enter your name</span>";
}
//CHECK IF EMAIL IS EMPTY
if (isset($email) === true && empty($email) === true) {
$mail_error = "<span class='error_text'>* Please enter your email address</span>";
//AND IF IT ISN'T EMPTY CHECK IF IT IS A VALID ONE
}
elseif (!isValidEmail($email)) {
$mail_error = "<span class='error_text'> * Please enter a valid email</span>";
}
//CHECK IF MESSAGE IS EMPTY
if (isset($message) === true && empty($message) === true) {
$message_error = "<span class='error_text'>* Please enter your message</span>";
}
}
// This function tests whether the email address is valid
function isValidEmail($email){
$pattern = "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$";
if (eregi($pattern, $email))
{
return true;
} else
{
return false;
}
}
I know I shouldn't be using globals in the function, I don't know an alternative. The error messages are display beside each form element.
© Stack Overflow or respective owner