未定义的变量试图修复我的联系表单

时间:2013-07-18 01:36:58

标签: php email contact-form

我一直在尝试修改我的联系表单,其中数据可以通过电子邮件发送。但我似乎在开始时有一些错误。它在网页上说“未定义的变量”。我只是按照我一直在阅读的教程,我还不熟悉PHP。我现在正在使用XAMPP来运行我的PHP

以下是HTML标记

<html>

<head>
<title>Contact Form</title>
<link rel="stylesheet" href="style.css" />
</head>

<body>
<h1>Contact Form</h1>
<p class="error"> There are some misisng fields.</p>
<?php if($error == true) { ?>
<?php } if($sent == true) { ?>
<p class="sent">Thank you for sending your message</p><?php } ?>

<div class="contactform">
<form name="contact"  action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<label for="name">Name:</label>
<input type="text" name="name" />
<label for="email">Email:</label>
<input type="email" name="email" />
<label for="comments">Comments:</label>
<textarea name="comments"></textarea>
<input type="submit" name="submit" class="submit" value="submit" /> 
</form>
</div>

这是PHP代码

<?php if($_POST['submit']) {
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
    $error = true;
} else {

     $to = "clestcruz@gmail.com";

     $name = trim($_POST['name']);
     $email = trim($_POST['email']);
     $comments = trim($_POST['comments']);

     $subject = "Contact Form";

     $messages = "Name: $name \r\n Email: $email \r\n Comments: $comments";
     $headers = "From:" . $name;
     $mailsent = mail($to, $subject, $messages, $headers);

     if($mailsent){
         $sent= true;
    }
}
}
?>

</body>
</html>

Undefine Variables

<?php if($error == true) { ?>

<?php } if($sent == true) { ?>

if($_POST['submit']) {

2 个答案:

答案 0 :(得分:0)

这些行:

<?php if($error == true) { ?>
<?php } if($sent == true) { ?>

出现在HTML的顶部附近,但据我所知,目前还没有执行PHP,因此不会定义$error$sent

这一行:

if($_POST['submit']) {

正在测试一个值,但除非您的表单已提交,否则也不会定义。你可以用

更有效地测试这个
 if (isset($_POST['submit'])) {
   // do stuff
 }

答案 1 :(得分:0)

在使用变量之前尝试声明变量。如果你没有先传递一个值,PHP会发出通知。

<?php 
$error=false;
$sent=false;
if(isset($_POST['submit'])) {
if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['comments'])) {
    $error = true;
} else {

     $to = "clestcruz@gmail.com";

     $name = trim($_POST['name']);
     $email = trim($_POST['email']);
     $comments = trim($_POST['comments']);

     $subject = "Contact Form";

     $messages = "Name: $name \r\n Email: $email \r\n Comments: $comments";
     $headers = "From:" . $name;
     $mailsent = mail($to, $subject, $messages, $headers);

     if($mailsent){
         $sent= true;
    }
}
}
?>