两种表单发布操作 - 将数据传递到另一页并通过电子邮件发送数据

时间:2014-08-06 21:22:05

标签: php forms post

我目前正在处理一个需要两个帖子操作和一个提交按钮的表单。我不是非常精通PHP,只知道足以绕过当前的任务,直到现在。

以下是表单所在页面的代码:

<?php

if ($_POST) {
    if (empty($_POST['first']) || 
    empty($_POST['last']) || 
    empty($_POST['email']) ||
    empty($_POST['location'])) {
        $errors = 1;
    } elseif (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors = 2;
    } else {
        $to = "emailgoeshere@gmail.com";
        $subject = "Blah blah blah";
        $message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
        $message .= "Email: ".$_POST['email']."\n";
        $message .= "Cell Phone: ".$_POST['cell']."\n";
        $message .= "Location: ".$_POST['location']."\n";
        $from = $_POST['email'];
        $headers = "From:" . $from;
        mail($to,$subject,$message,$headers);
        header('Location: freepass.php');
        exit;
    }
}

if ($errors == 1) {
    $errors = "Please fill out all fields";
} elseif ($errors == 2) {
        $errors = "Please enter a valid email";
}

?>

这是表单操作:

<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">

这是数据传递给页面的代码:

<html>
<head>
</head>
<body>
<?php echo $_POST["first"]; ?> <?php echo $_POST["last"]; ?>
<br>
<?php echo $_POST["email"]; ?>
<br>
<?php echo $_POST["cell"]; ?>
<br>
<?php echo $_POST["location"]; ?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

这是一个非常快速的解决方案,但它应该可以解决问题。

if ($_POST) {
    $errors = null;
    $error_message = "<ul>";

    if (empty($_POST['first']) || 
        empty($_POST['last']) || 
        empty($_POST['email']) || 
        empty($_POST['location'])) {
        $errors = 1;
    } 

    if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $errors = 2;
    }

    if($errors == null) {
        $to = "grimegriever@gmail.com";
        $subject = "City Fitness 7-Day Pass Applicant";
        $message .= "Name: ".$_POST['first']." ".$_POST['last']."\n";
        $message .= "Email: ".$_POST['email']."\n";
        $message .= "Cell Phone: ".$_POST['cell']."\n";
        $message .= "Location: ".$_POST['location']."\n";
        $from = $_POST['email'];
        $headers = "From:" . $from;

        mail($to, $subject, $message, $headers);
        header('Location: freepass.php');
        exit;
    } else {
        if ($errors == 1) {
            $error_message .= "<li>Please fill out all fields</li>";
        }

        if ($errors == 2) {
            $error_message .= "<li>Please enter a valid email</li>";
        }

        $error_message .= "</ul>";
    }
}

我确信有更高效的解决方案,但这会奏效。