PHP,正在尝试向现有表单添加验证码

PHP,正在尝试向现有表单添加验证码,php,forms,captcha,Php,Forms,Captcha,我不是一个PHP程序员,但我使用过它,足以让它成为一种联系方式。但是,我正在尝试添加一个captcha字段,该字段现在可以工作,但表单无法验证它-因此无论发生什么情况,它都会提交 有人能帮忙吗?抱歉,如果代码混乱,请提前感谢 代码在我的页面顶部 <?php session_start() ?> <?php //If the form is submitted if(isset($_POST['submit'])) {

我不是一个PHP程序员,但我使用过它,足以让它成为一种联系方式。但是,我正在尝试添加一个captcha字段,该字段现在可以工作,但表单无法验证它-因此无论发生什么情况,它都会提交

有人能帮忙吗?抱歉,如果代码混乱,请提前感谢

代码在我的页面顶部

        <?php session_start() ?> 
<?php  
      //If the form is submitted  
    if(isset($_POST['submit'])) {  

    //Check to make sure that the name field is not empty  
     if(trim($_POST['name']) == '') {  
         $hasError = true;  
     } else {  
         $name = trim($_POST['name']);  
     }  

       //Check to make sure that the subject field is not empty  
    if(trim($_POST['subject']) == '') {  
         $hasError = true;  
     } else {  
         $subject = trim($_POST['subject']);  
     }  

    //Check to make sure sure that a valid email address is submitted  
     if(trim($_POST['email']) == '')  {  
         $hasError = true;  
     } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) 
     {  
         $hasError = true;  
     } else {  
         $email = trim($_POST['email']);  
     }  

    //Check to make sure comments were entered  
    if(trim($_POST['message']) == '') {  
         $hasError = true;  
     } else {  
    if(function_exists('stripslashes')) {  
         $message = stripslashes(trim($_POST['message']));  
     } else {  
         $message = trim($_POST['message']);  
     } 

     /*captcha 2*/ 

    if(isset($_POST["captcha"])) {
        $hasError = true;
    } else {
    if($_SESSION["captcha"]==$_POST["captcha"]) {
    }
    }
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...

    //If there is no error, send the email  
     if(!isset($hasError)) {  
         $emailTo = 'email address'; //Put your own email address here  
         $emailTo = 'email address'; //Put your own email address here  
         $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";  
         $headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .         
         $email;  

    mail($emailTo, $subject, $body, $headers);  
         $emailSent = true;  
     }
     }
?> 

   Code in the form:

    [php]<?php if(isset($hasError)) { //If errors are found ?>  

        <p class="error">Please check if you've filled all the fields with valid information.           Thank    you.</p>  
  <?php } ?>  

  <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>  
      <p><strong>Email Successfully Sent!</strong></p>  
      <p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>  
      <?php } ?>  

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

         <p>
         <label for="name">Name</label><br />
         <input type="text" name="name" value="" id="name" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="email">Email</label><br />
         <input type="text" name="email" value="" id="email" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="subject">Subject</label><br />
         <input type="text" name="subject" value="" id="subject" class="required">
         </p> 

     </div>  

     <div style="margin-bottom:25px;">  

         <p>
         <label for="message">Message</label><br />
         <textarea rows="5" name="message" value="" id="message" class="required"></textarea>
         </p> 

     </div>  
     <div style="margin-bottom:25px;">  


         <img src="captcha.php" alt="captcha image">
         <p>
         <label for="captcha">(antispam code, 3 black symbols)</label><br />
         <input type="text" name="captcha" maxlength="3" id="captcha" class="required">
         </p> 

     </div>  
     <input type="submit" value="Send Message" name="submit" />  
 </form>
 [/php]

表格中的代码:
[菲律宾]

请检查您是否用有效信息填写了所有字段。谢谢。

电子邮件已成功发送

感谢您与我们联系。您的电子邮件已成功发送,我们将很快与您联系。

如果(isset($_POST[“验证码]))

你少了一个括号

已编辑以显示整个代码。。。。为缺少的验证码条件添加括号。实际上,您的代码没有检查验证码是否是通过post设置的。它只是对照post变量检查会话变量。如果两者都为空,则表单将通过邮件发送。您可能仍然存在captcha.php或会话变量问题

<?php  
      //If the form is submitted  
    if(isset($_POST['submit'])) {  

    //Check to make sure that the name field is not empty  
     if(trim($_POST['name']) == '') {  
         $hasError = true;  
     } else {  
         $name = trim($_POST['name']);  
     }  

       //Check to make sure that the subject field is not empty  
    if(trim($_POST['subject']) == '') {  
         $hasError = true;  
     } else {  
         $subject = trim($_POST['subject']);  
     }  

    //Check to make sure sure that a valid email address is submitted  
     if(trim($_POST['email']) == '')  {  
         $hasError = true;  
     } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) 
     {  
         $hasError = true;  
     } else {  
         $email = trim($_POST['email']);  
     }  

    //Check to make sure comments were entered  
    if(trim($_POST['message']) == '') {  
         $hasError = true;  
     } else {  
    if(function_exists('stripslashes')) {  
         $message = stripslashes(trim($_POST['message']));  
     } else {  
         $message = trim($_POST['message']);  
     }  
     }

     /*captcha 2*/ 


    if(isset($_POST["captcha"])) {
    if($_SESSION["captcha"]==$_POST["captcha"])
    {
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...

    //If there is no error, send the email  
     if(!isset($hasError)) {  
         $emailTo = 'enquiries@sjbprojects.com'; //Put your own email address here  
         $emailTo = 'sjbullen@gmail.com'; //Put your own email address here  
         $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";  
         $headers = 'From: SJB Projects website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .          $email;  

    mail($emailTo, $subject, $body, $headers);  
         $emailSent = true;  
    }
   else
    {
    echo 'CAPTHCA is not valid; ignore submission';
    }
    }  


    } else {

     ///message here if CAPTCHA is not set (via post)

    }

    }  
     ?> 

  <?php if(isset($hasError)) { //If errors are found ?>  

        <p class="error">Please check if you've filled all the fields with valid information.           Thank    you.</p>  
  <?php } ?>  

  <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>  
      <p><strong>Email Successfully Sent!</strong></p>  
      <p>Thank you <strong><?php echo $name;?></strong> for contacting SJB Projects. Your email was successfully sent and we will be in touch with you soon.</p>  
      <?php } ?>  

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

         <p>
         <label for="name">Name</label><br />
         <input type="text" name="name" value="" id="name" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="email">Email</label><br />
         <input type="text" name="email" value="" id="email" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="subject">Subject</label><br />
         <input type="text" name="subject" value="" id="subject" class="required">
         </p> 

     </div>  

     <div style="margin-bottom:25px;">  

         <p>
         <label for="message">Message</label><br />
         <textarea rows="5" name="message" value="" id="message" class="required"></textarea>
         </p> 

     </div>  
     <div style="margin-bottom:25px;">  


         <img src="captcha.php" alt="captcha image">
         <p>
         <label for="captcha">(antispam code, 3 black symbols)</label><br />
         <input type="text" name="captcha" maxlength="3" id="captcha" class="required">
         </p> 

     </div>  
     <input type="submit" value="Send Message" name="submit" />  
 </form>

请检查您是否用有效信息填写了所有字段。谢谢。

电子邮件已成功发送

感谢您联系SJB项目。您的电子邮件已成功发送,我们将很快与您联系。

如果(isset($_POST[“验证码]))

你少了一个括号

已编辑以显示整个代码。。。。为缺少的验证码条件添加括号。实际上,您的代码没有检查验证码是否是通过post设置的。它只是对照post变量检查会话变量。如果两者都为空,则表单将通过邮件发送。您可能仍然存在captcha.php或会话变量问题

<?php  
      //If the form is submitted  
    if(isset($_POST['submit'])) {  

    //Check to make sure that the name field is not empty  
     if(trim($_POST['name']) == '') {  
         $hasError = true;  
     } else {  
         $name = trim($_POST['name']);  
     }  

       //Check to make sure that the subject field is not empty  
    if(trim($_POST['subject']) == '') {  
         $hasError = true;  
     } else {  
         $subject = trim($_POST['subject']);  
     }  

    //Check to make sure sure that a valid email address is submitted  
     if(trim($_POST['email']) == '')  {  
         $hasError = true;  
     } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) 
     {  
         $hasError = true;  
     } else {  
         $email = trim($_POST['email']);  
     }  

    //Check to make sure comments were entered  
    if(trim($_POST['message']) == '') {  
         $hasError = true;  
     } else {  
    if(function_exists('stripslashes')) {  
         $message = stripslashes(trim($_POST['message']));  
     } else {  
         $message = trim($_POST['message']);  
     }  
     }

     /*captcha 2*/ 


    if(isset($_POST["captcha"])) {
    if($_SESSION["captcha"]==$_POST["captcha"])
    {
    //CAPTHCA is valid; proceed the message: save to database, send by e-mail ...

    //If there is no error, send the email  
     if(!isset($hasError)) {  
         $emailTo = 'enquiries@sjbprojects.com'; //Put your own email address here  
         $emailTo = 'sjbullen@gmail.com'; //Put your own email address here  
         $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";  
         $headers = 'From: SJB Projects website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' .          $email;  

    mail($emailTo, $subject, $body, $headers);  
         $emailSent = true;  
    }
   else
    {
    echo 'CAPTHCA is not valid; ignore submission';
    }
    }  


    } else {

     ///message here if CAPTCHA is not set (via post)

    }

    }  
     ?> 

  <?php if(isset($hasError)) { //If errors are found ?>  

        <p class="error">Please check if you've filled all the fields with valid information.           Thank    you.</p>  
  <?php } ?>  

  <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>  
      <p><strong>Email Successfully Sent!</strong></p>  
      <p>Thank you <strong><?php echo $name;?></strong> for contacting SJB Projects. Your email was successfully sent and we will be in touch with you soon.</p>  
      <?php } ?>  

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

         <p>
         <label for="name">Name</label><br />
         <input type="text" name="name" value="" id="name" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="email">Email</label><br />
         <input type="text" name="email" value="" id="email" class="required">
         </p> 
     </div>  

     <div>  

         <p>
         <label for="subject">Subject</label><br />
         <input type="text" name="subject" value="" id="subject" class="required">
         </p> 

     </div>  

     <div style="margin-bottom:25px;">  

         <p>
         <label for="message">Message</label><br />
         <textarea rows="5" name="message" value="" id="message" class="required"></textarea>
         </p> 

     </div>  
     <div style="margin-bottom:25px;">  


         <img src="captcha.php" alt="captcha image">
         <p>
         <label for="captcha">(antispam code, 3 black symbols)</label><br />
         <input type="text" name="captcha" maxlength="3" id="captcha" class="required">
         </p> 

     </div>  
     <input type="submit" value="Send Message" name="submit" />  
 </form>

请检查您是否用有效信息填写了所有字段。谢谢。

电子邮件已成功发送

感谢您联系SJB项目。您的电子邮件已成功发送,我们将很快与您联系。

[编辑]2011-12-20 8:22pm CST-根据场外聊天,用OP使用的最终代码更新了第二段代码。

有一种更好的方法来编写代码。我在下面举一个例子。提出问题,我会用注释更新代码。我修改了验证码的if语句,这样就不需要双
if
。在
if
语句中使用
|
(或)会导致PHP在测试第一个条件后停止(如果第一个条件的计算结果为true)。因此,如果未设置该变量,它将永远不会进行POST与SESSION的比较

另外,我将hasError变量默认为false,并且正在测试布尔值。这是更好的,因为它是有意义的。想想那些会追上你的程序员。如果说得通的话,就更容易合作了。你可能就是那个程序员:)

[编辑以添加
会话_start();
]

[edit]2011-12-20 8:22pm CST-根据场外聊天,用OP使用的最终代码更新了第二段代码。

有一种更好的方法来编写代码。我在下面举一个例子。提出问题,我会用注释更新代码。我修改了验证码的if语句,这样就不需要双
if
。在
if
语句中使用
|
(或)会导致PHP在测试第一个条件后停止(如果第一个条件的计算结果为true)。因此,如果未设置该变量,它将永远不会进行POST与SESSION的比较

另外,我将hasError变量默认为false,并且正在测试布尔值。这是更好的,因为它是有意义的。想想那些会追上你的程序员。如果说得通的话,就更容易合作了。你可能就是那个程序员:)

[编辑以添加
会话_start();
]


您的文件是否调用了session_start()?如果没有它,$\u会话['catpcha']将为空(并可能抛出通知)。另外,请注意,您应该检查存储的captcha值是否为空。否则,用户只需通过不加载图像来传递验证码即可。如果(!empty($\u SESSION['captcha'])&&$\u SESSION['captcha']==$captcharomuser){valid}检查会话存储的captcha值是否为空?这是我在上面发布的代码。顺便说一句,$captchaFromUser就是$u POST['captcha']。通常最好避免直接访问$\u POST值,而不检查它们是否已先设置。如果没有设置,那么你会收到通知。很抱歉,我以前没有看到代码,所以我将If(isset($\u POST[“captcha]”)替换为If(!empty($\u SESSION['captcha]])&&$\u SESSION['captcha]===$captcharomuser),所以现在,即使没有输入captcha,它似乎仍然提交,但随后它会清除所有表单字段,并且没有错误消息-就像再次开始一样…对不起,感谢您的帮助,我已经花了3个晚上试图解决这个问题,我想我需要一位专家!您的文件是否有对会话_start()的调用?如果没有它,$\u会话['catpcha']将为空(并可能抛出通知)。另外,请注意,您应该检查存储的captcha值是否为空。否则,用户只需通过不加载图像来传递验证码即可。如果(!empty($\u SESSION['captcha'])&&$\u SESSION['captcha']==$captcharomuser){valid}检查会话存储的captcha值是否为空?这是我在上面发布的代码。顺便说一句,$captchaFromUser就是$u POST['captcha']。通常,最好避免使用直接访问$\u POST值
    <?php
session_start();

function clean_for_email( $inbound )
{
   return str_replace( array( "\n", "\r" ), "", $inbound );
}
// I really like the name of this function. :D
function outputInput( $name, $required )
{
    $attribs[] = "name=\"{$name}\"";
    $attribs[] = "id=\"{$name}\"";
    $attribs[] = $required?'class="required"':'';
    $attribs[] = 'type="text"';


    if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
    {
        $attribs[] = 'value="' . htmlspecialchars( $_POST[$name] ) . '"';
    }

    echo '<input ' . implode( ' ', $attribs ) . '>';
}
//------------------------------------------------------------------------
function outputTextarea( $name, $required, $rows = 5 )
{
    $attribs[] = "name=\"{$name}\"";
    $attribs[] = "id=\"{$name}\"";
    $attribs[] = $required?'class="required"':'';
    $attribs[] = 'rows="5"';
    $value = '';

    if ( count( $_POST ) && array_key_exists( $name, $_POST ) )
    {
        $value = htmlspecialchars( $_POST[$name] );
    }

    echo '<textarea ' . implode( ' ', $attribs ) . '>' . $value . '</textarea>';
}

// default value
$hasError = false;
$emailSent = false;

//If the form is submitted
if( count( $_POST ) && isset($_POST['submit'] ) ) {
    //Check to make sure that the name field is not empty
    if(trim($_POST['name']) == '') {
        $hasError = true;
    } else {
        $name = trim($_POST['name']);
    }

    //Check to make sure that the subject field is not empty
    if(trim($_POST['subject']) == '') {
        $hasError = true;
    } else {
        $subject = trim($_POST['subject']);
    }

    //Check to make sure sure that a valid email address is submitted
    if(trim($_POST['email']) == '')  {
        $hasError = true;
    } else if ( ! preg_match( '/^.+@.+$/i', trim( $_POST['email'] ) ) ) {
        $hasError = true;
    } else {
        $email = trim($_POST['email']);
    }

    //Check to make sure comments were entered
    if( trim($_POST['message']) == '') {
        $hasError = true;
    } else {
        if(function_exists('stripslashes')) {
            $message = stripslashes(trim($_POST['message']));
        } else {
            $message = trim($_POST['message']);
        }  
    }

    if ( ! array_key_exists( 'captcha', $_POST ) || $_SESSION['captcha'] != $_POST["captcha"] ) {
        $hasError = true;
    }

    if( ! $hasError )
    {
        $captchaValid = true;
        //If there is no error, send the email
        if( $hasError == false ) {
            $emailTo = 'xxx'; //Put your own email address here
            $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";
            $headers = 'From: website form <'.clean_for_email( $emailTo ).'>' . "\r\n" . 'Reply-To: ' . clean_for_email( $email );
            mail($emailTo, $subject, $body, $headers);
            $emailSent = true;
        } else {

        }
    }
}
?>

<? if( $hasError ) : ?>
    <p class="error">Please check if you've filled all the fields with valid information Thank you.</p>  
<? endif; ?>

<? if( $emailSent == true) : ?>
    <p><strong>Email Successfully Sent!</strong></p>  
    <p>Thank you <strong><?php echo $name;?></strong> for contacting us. Your email was successfully sent and we will be in touch with you soon.</p>  
<? endif; ?>  

 <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" id="contactform">  
    <div>  
        <p>
        <label for="name">Name</label><br />
        <? outputInput( 'name', true ); ?>
        </p> 
    </div>  

    <div>  
        <p>
        <label for="email">Email</label><br />
        <? outputInput( 'email', true ); ?>
        </p> 
    </div>  

    <div>  
        <p>
        <label for="subject">Subject</label><br />
        <? outputInput( 'subject', true ); ?>
        </p> 
    </div>  

    <div style="margin-bottom:25px;">  
        <p>
        <label for="message">Message</label><br />
        <? outputTextarea( 'message', true ); ?>
        </p> 
    </div>  
    <div style="margin-bottom:25px;">  
        <img src="captcha.php" alt="captcha image">
        <p>
        <label for="captcha">(antispam code, 3 black symbols)</label><br />
        <? outputInput( 'captcha', true ); ?>
        </p> 
    </div>  
    <input type="submit" value="Send Message" name="submit" />  
</form>