Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6960981
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T15:28:16+00:00 2026-05-27T15:28:16+00:00

I am not a PHP programmer, but have used it a touch, enough to

  • 0

I am not a PHP programmer, but have used it a touch, enough to put in a contact form. However, I am trying to add a captcha field, which now works but the form does not validate it – so it submits no matter what

Can anybody help please? sorry if the code is messy and thanks in advance

code at the top of my page

        <?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]
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T15:28:17+00:00Added an answer on May 27, 2026 at 3:28 pm

    [edit ] 2011-12-20 8:22pm CST – updated the second block of code with the final code that the OP is using – based on off site chat.

    There’s a better way to write the code. I’m putting an example of this below. Ask questions and I’ll update the code with comments explaining. I revamped the if statement you had for the captcha so that it didn’t need a double if. Using || (or) in the if statement causes PHP to stop after testing the first condition (if the first condition evaluates to true). Therefore, if the variable is not set it never moves on to the comparison of POST with SESSION.

    Also, I defaulted your hasError variable to false, and am testing for the boolean value. This is better because it makes sense. Think about the programmers who will come after you. If it makes sense, it’ll be easier to work with. You might be that programmer 🙂

    [edited to add session_start();]

    <?php
    session_start();
    
    // default value
    $hasError = false;
    
    //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']);
            }  
        }
    
        if( ! isset( $_POST["captcha"] ) || $_SESSION["captcha"] != $_POST["captcha"] ) {
            $hasError = true;
            echo 'CAPTHCA is not valid; ignore submission<br>';
            echo $_POST['captcha' . ' != ' . $_SESSION['captcha'] . '<br>';
        }
    
        //If there is no error, send the email  
        if( $hasError == false ) {  
            $emailTo = 'email@email.com'; //Put your own email address here  
            $emailTo = 'email@email.com'; //Put your own email address here  
            $body = "Name: $name \n\nEmail: $email \n\nSubject: $subject \n\nMessage:\n $message";  
    
            // !!!!!!!!!!!!!!!! REMOVE \r\n from $emailTo or your form will be hacked !!!!!!!!!!!!!!!!!!!!!!
            $headers = 'From: website form <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;  
    
            mail($emailTo, $subject, $body, $headers);  
            $emailSent = true;  
        } else {
    
        }
    }
    

    [edit – full code, edited and (hopefully) improved]

        <?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>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am not a PHP programmer but have tweaked some in the past. How
I'm new to PHP and web development in general, but have been a programmer
I am an experienced PHP programmer, but I have been looking into Ruby lately,
OK first of all, I am a PHP programmer but I have never done
I'm not a PHP developer but i've seen in a couple of places that
Is it possible to have php not to require the begin/end tags ( <?php
I am a php programmer, but new to zend framework. I want to upload
I have a little page I've been working on. It's at: http://nait.jtlnet.com/~fpkj5v0r/programmer.php - and
So let me apologize right up front. I'm not a PHP programmer, I'm a
First of all I want to say I am not a programmer but I

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.