Contact form with PHP, am I doing it wrong?

I am learning PHP and I am trying to write a simple email script. I have a function (checkEmpty) to check if all forms have been completed and if the email address is valid (isEmailValid). I'm not sure how to return true checkempty funciton. Here's my code:

On clicking the submit button:

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 use global functions in a function, I don't know of an alternative. Error messages are displayed next to each form element.

+2


a source to share


3 answers


First of all, using the global is a sin. You are polluting the global namespace, which is a bad idea except for small ad-hoc scripts and legacy code.

Secondly, you are using isset incorrectly - for two reasons: a) in the given context, you are passing the $ name variable to the function, so it is always set b) empty checks whether the variable is set or not

Third, you must separate the validation from the html generation.



Fourth, you can use filter_var instead of a regular expression to validate mail.

Finally, your code might look like this:

<?php

if (isset($_POST['submit'])) {

$fields = array ('name' => $_POST['name'], 'email' => $_POST['email'], 'message' =>     $_POST['message']);

//CONVERT ARRAY KEYS TO VARIABLE NAMES
extract ($fields);  

$errors = validateFields($name, $email, $message);

if (!empty($errors)){

    # error 

    foreach ($errors as $error){

        print "<p class='error'>$error</p>";

    }

} else {

    # all ok, do your stuff

} // if

} // if

function validateFields($name, $email, $post){

    $errors = array();

        if (empty($name)){$errors[] = "Name can't be empty";}
        if (empty($email)){$errors[] = "Email can't be empty";}
        if (empty($post)){$errors[] = "Post can't be empty";}

        if (!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL)){$errors[] = "Invalid email";}
        if (!empty($post) && strlen($post)<10){$errors[] = "Post too short (minimum 10 characters)";}

    # and so on...

    return $errors;

}

      

0


a source


First of all, you should really rethink your logic to avoid globals.

In the meantime, create a $ success variable and set it to true at the top of your functions. If any if statement fails, set it to false. Then return $ success at the bottom of your function. Example:



function checkExample($txt) {
    $success = true;

    if (isset($txt) === true && empty($txt) === true) {
        $error = "<span class='error_text'>* Please enter your example text</span>";
        $success = false;
    }

    return $success;
}

      

0


a source


I'm not sure if this is what you want, as I see it, you want $ mail_error, $ message_error and $ name_error to be accessible from outside the function. If so, you need something like this:

function checkEmpty($name, $email, $message) {  
    $results = false;

    //CHECK IF NAME FIELD IS EMPTY
    if (isset($name) === true && empty($name) === true) {
      $results['name_error'] = "<span class='error_text'>* Please enter your name</span>";
    }

    //CHECK IF EMAIL IS EMPTY
    if (isset($email) === true && empty($email) === true) {
      $results['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)) {
        $results['mail_error'] = "<span class='error_text'> * Please enter a valid email</span>"; 
    }

    //CHECK IF MESSAGE IS EMPTY
    if (isset($message) === true && empty($message) === true) {
      $results['message_error'] = "<span class='error_text'>* Please enter your message</span>";
    }

    return $results;
} 
$errors = checkEmpty($name, $email, $message);

      

now you can check for errors

if($errors){
    extract ($errors); // or simply extract variables from array to be used next to form inputs
} else {
    // there are no errors, do other thing if needed...
}

      

0


a source







All Articles