简体   繁体   English

PHP联系表格,我做错了吗?

[英]PHP contact form, am I doing it wrong?

I'm learning PHP and I'm trying to write a simple email script. 我正在学习PHP,并且试图编写一个简单的电子邮件脚本。 I have a function (checkEmpty) to check if all the forms are filled in and if the email adress is valid (isEmailValid). 我有一个函数(checkEmpty)来检查是否填写了所有表格,以及电子邮件地址是否有效(isEmailValid)。 I'm not sure how to return true checkEmpty funciton. 我不确定如何返回真实的checkEmpty函数。 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. 错误消息显示在每个表单元素旁边。

First of all, you should really re-think your logic as to avoid global variables. 首先,您应该重新考虑自己的逻辑,以避免全局变量。

Eitherway, create a variable $success and set it to true in the top of your functions. 无论哪种方式,都需要在函数顶部创建一个变量$ success并将其设置为true。 If any if statement fails, set it to false. 如果任何if语句失败,请将其设置为false。 Then return $success in the bottom of your function. 然后在函数底部返回$ success。 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;
}

I'm not sure this is what you want, the way I see it, you want $mail_error, $message_error and $name_error to be accessible from outside the function. 我不确定这是您想要的东西,还是我希望通过功能外部访问$ mail_error,$ message_error和$ name_error。 If that's the case, what you need is 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 test 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...
}

First of all, using global is a sin. 首先,使用全局是一种罪过。 You are polluting global namespace, and this is bad idea, except little ad-hoc scripts and legacy code. 您正在污染全局名称空间,这是个坏主意,除了很少的即席脚本和旧代码之外。

Second, you are misusing isset - for two reasons: a ) in given context you pass variable $name to function, so it is always set b ) empty checks whether variable is set or not 其次,您正在滥用isset-出于两个原因:a)在给定的上下文中,您将变量$ name传递给函数,因此始终将其设置为b)empty检查是否设置了变量

Third, you should separate validation from generating html. 第三,您应该将验证与生成html分开。

Fourth, you can use filter_var instead of regular expression to test if mail is valid. 第四,您可以使用filter_var而不是正则表达式来测试邮件是否有效。

Last, your code could look like that: 最后,您的代码可能如下所示:

<?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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM