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

发布于 2024-09-01 01:24:18 字数 1743 浏览 4 评论 0原文

我正在学习 PHP,正在尝试编写一个简单的电子邮件脚本。我有一个函数(checkEmpty)来检查是否填写了所有表格以及电子邮件地址是否有效(isEmailValid)。我不知道如何返回真正的 checkEmpty 函数。这是我的代码:

单击提交按钮时:

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'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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

千紇 2024-09-08 01:24:18

首先,使用 global 是一种罪过。您正在污染全局名称空间,这是一个坏主意,除了少量的临时脚本和遗留代码。

其次,您滥用 isset - 原因有两个:
a)在给定的上下文中,您将变量 $name 传递给函数,因此它始终被设置
b) 空检查变量是否设置

第三,您应该将验证与生成 html 分开。

第四,可以使用filter_var代替正则表达式来测试邮件是否有效。

最后,您的代码可能如下所示:

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

}

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

Third, you should separate validation from generating html.

Fourth, you can use filter_var instead of regular expression to test if mail is valid.

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;

}
天邊彩虹 2024-09-08 01:24:18

首先,您应该真正重新思考您的逻辑以避免全局变量。

不管怎样,创建一个变量 $success 并在函数顶部将其设置为 true。如果任何 if 语句失败,请将其设置为 false。然后在函数底部返回 $success 。例子:

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

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. If any if statement fails, set it to false. Then return $success in 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;
}
能怎样 2024-09-08 01:24:18

我不确定这是否是您想要的,在我看来,您希望 $mail_error、$message_error 和 $name_error 可以从函数外部访问。如果是这样的话,您需要的是这样的:

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

现在您可以测试错误

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...
}

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. 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...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文