为什么在以PHP表单提交数据之前会出现此验证错误?


Why does this validation error occur before data is submitted in PHP form?

我使用PHP表单将数据转发到电子邮件地址。一切似乎都很好,除了错误信息["你没有输入一个电子邮件"]出现在页面加载时,在用户输入任何输入之前,而不是在提交时通过验证。

表单在这里http://www.soulwatt.com/contact.php

注意:我发现这个PHP代码在网上做如何转发数据到电子邮件的搜索后,所以它不是我的。请原谅缺少适当的代码格式。

<?php 
 $to = $_REQUEST['sendto'] ; 
 $from = $_REQUEST['Email'] ; 
 $name = $_REQUEST['Name'] ; 
 $headers = "From: $from"; 
 $subject = "soulwatt.com Contact Data!!"; 
 $fields = array(); 
 $fields{"Name"} = "Name"; 
 $fields{"Company"} = "Company"; 
 $fields{"Email"} = "Email"; 
 $fields{"Phone"} = "Phone"; 
 $fields{"list"} = "Mailing List"; 
 $fields{"Comments"} = "Comments"; 
 $body = "Soul Watt has received the following information:'n'n";
 foreach($fields as $a => $b)   {
    $body .= sprintf("%20s: %s'n",$b,$_REQUEST[$a]);
    } 
 $headers2 = "From: noreply@soulwatt.com";
 $subject2 = "Thank you for contacting Soul Watt!"; 
 $autoreply = "Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.soulwatt.com";
 if($from == '') {
      print "You have not entered an email. Please enter your email and try again.";
      } 
 else {
 if($name == '') {
      print "You have not entered a name.<br />Please enter your name and try again.";
      } 
 else { 
 $send = mail($to, $subject, $body, $headers); 
 $send2 = mail($from, $subject2, $autoreply, $headers2);
 if($send)  {
     print "<p><span>THANK YOU FOR CONTACTING US!</span></p>";
     print "<p><span>Someone will get back to you as soon as possible, usually within 48 hours. If you need immediate assistance regarding booking Soul Watt, please call Randy at (828) 729-3199.</span></p>";
     }
 else  {
     print "<p><span>We encountered an error sending your mail, please notify webmaster@soulwatt.com</span></p>";
     } 
 }
}?>

谢谢你的帮助!

这两行:

$from = $_REQUEST['Email'] ; 
if($from == '') {
   print "You have not entered an email. Please enter your email and try again.";
}

表示检查email请求(POSTGET)键。当你第一次加载这个页面时,它将是空的。您可以添加检查是否存在POST,例如是否有提交。

老实说,你的代码可能会有很多问题:用户可以在那里添加各种各样的东西,甚至可能在标题中添加东西来添加' To '字段等等。你可能在制造一个垃圾邮件机器。这部分:$headers = "From: $from";只是添加请求字段FROM在您的头....

您需要将验证部分包装在

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    ... do validation here ...
}
... print form here ...

只在提交表单后运行验证代码。现在,它在每次加载页面时都在运行,所以当然没有表单数据来验证第一次。

您的表单字段是否有相同的名称,您正在检查?

我的意思是

$from = $_REQUEST['Email'];

你应该有

<input type='text' name='Email' /> <!-- Note the Capital E -->

我在这里添加了我的评论:

使用$_POST或$_GET。避免$ _REQUEST。这样你就可以更好地控制你的应用。

另外,不要用=="来检查是否为空try empty($from)

好的如果表单在http://www.soulwatt.com/contact.php上,而你有

<form method="post" action="contact.php" name="contact_form" id="contact_form">

action="contact.php":这意味着它在同一地址上处理表单,所以您将在同一页面上看到表单处理的结果,并且由于表单是空的,并且您正在检查它,无论它是否已发布,您会得到错误