Contact page with math security number

My contact page doesn’t work when I put the math security number to be checked. This is the live contact page http://aproapetot.ro/contact.php

and this is the php contact page with the math security. Please, someone tell me where I made a mistake.

<script language="javascript" type="text/javascript">
    // this is just a simple reload; you can safely remove it; remember to remove it from the image too 
    function reloadCaptcha()
    {
        document.getElementById('captcha').src = document.getElementById('captcha').src+ '?' +new Date();
    }
</script>

<?php
if (isset($_POST['contact'])) { // Handle the form.

    // Need the database connection:
    //require ('includes/mysql.inc.php');
    
    // Trim all the incoming data:
    $trimmed = array_map('trim', $_POST);

    // Assume invalid values:
    $fn = $ln = $email = $mesaj = $secure = FALSE;
    
    // Check for a first name:
    if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
        $fn = $trimmed['first_name'];
    } else {
        echo '<p class="error">Va rugam sa introduceti prenumele !</p>';
    }

    // Check for a last name:
    if (preg_match ('/^[A-Z \'.-]{2,40}$/i', $trimmed['last_name'])) {
        $ln =  $trimmed['last_name'];
    } else {
        echo '<p class="error">Va rugam sa introduceti nummele !</p>';
    }
    
    // Check for an email address:
    if (filter_var($trimmed['email'], FILTER_VALIDATE_EMAIL)) {
        $email = $trimmed['email'];
    } else {
        echo '<p class="error">Adresa de email nu este valida !</p>';
    }
    
    // Check for a message:
    if (isset($_POST['mesaj'] )) {
        $mesaj = $_POST['mesaj'];
    } else {
        echo '<p class="error">Va rugam sa introduceti mesajul !</p>';
    }
    
    // Check for a security number:
    if((isset($_POST['secure'])) ==  $_SESSION['security_number']){
        $secure = $_POST['secure'];
    } else {        
        echo '<p class="error">Va rugam verificati codul de validare!</p>';
    }
    
    if($fn && $ln && $email && $mesaj &&  $secure) {  // If everything's OK...
                        
                            
            
            
                // Create the body:
                $body = " DATE PERSONALE \n\n 
                        Nume: $ln \n 
                        Prenume: $fn \n  
                        Email: $email \n\n 
                        MESAJ \n $mesaj \n ";
        
                // Make it no longer than 70 characters long:
                $body = wordwrap($body, 100);
            
                // Send the email:
                mail('@yahoo.com', 'Contact Form Submission', $body, "From:$email");
        
                // Print a message:
                echo '<p><em>Va multumim ca ne-ati contactat. O sa va raspundem cat mai repede posibil.</em></p>';
            
        
    } else { // If one of the data tests failed.
        echo '<p class="error">Va rugam sa incercati din nou.</p>';
    }



} // End of the main Submit conditional.
?>
 

<form action="contact.php" method="post" class="basic-grey">
    <h1>Pagina de Contact</h1>
    <label>
        <span>Prenumele:</span>
         <input type="text" name="first_name" size="20" maxlength="20" value="<?php if (isset($trimmed['first_name'])) echo $trimmed['first_name']; ?>" />
    </label>    
    <label>
        <span>Numele:</span>
         <input type="text" name="last_name" size="20" maxlength="40" value="<?php if (isset($trimmed['last_name'])) echo $trimmed['last_name']; ?>" />
    </label>    
    <label>
        <span>Email:</span>
         <input type="text" name="email" size="30" maxlength="60" value="<?php if (isset($trimmed['email'])) echo $trimmed['email']; ?>" />
    </label>    
    <label>
        <span>Mesaj:</span>
         <textarea  name="mesaj" value="<?php if (isset($_POST['mesaj'])) echo $_POST['mesaj']; ?>" /></textarea>
    </label>    
    <label>
        <span class="explain">click pe imagine pentru reincarcare</span>
               <img src="library/image.php" alt="Click to reload image" title="Click to reload image" id="captcha" onclick="javascript:reloadCaptcha()" />
    </label>
    <label>
        <span>Scrieti rezultatul</span>
        <input type="text" class="contact_math" name="secure" value="<?php if (isset($__POST['secure'])) echo $_POST['secure']; ?>" onclick="this.value=''" />
     </label>
     <label>
        <span>&nbsp;</span>
       <input type="submit" name="contact" class="button" value="Trimite" />
    </label>
</form>

Did you mean to compare the result of isset() to the session variable here? I can’t see where you set that session variable so it might be correct.

    // Check for a security number:
    if((isset($_POST['secure'])) ==  $_SESSION['security_number']){
        $secure = $_POST['secure'];
    } else {        
        echo '<p class="error">Va rugam verificati codul de validare!</p>';
    }

The security number comes from the this page. I don’t understand why even I put the security number doesn’t let me to sent the message.

    /*===============================================================
        General captcha settings
      ===============================================================*/
    // captcha width
    $captcha_w = 205;
    // captcha height
    $captcha_h = 50;
    // minimum font size; each operation element changes size
    $min_font_size = 12;
    // maximum font size
    $max_font_size = 18;
    // rotation angle
    $angle = 20;
    // background grid size
    $bg_size = 13;
    // path to font - needed to display the operation elements
    $font_path = '../library/fonts/courbd.ttf';
    // array of possible operators
    $operators=array('+','-','*');
    // first number random value; keep it lower than $second_num
    $first_num = rand(1,5);
    // second number random value
    $second_num = rand(6,11);
        
    /*===============================================================
        From here on you may leave the code intact unless you want
        or need to make it specific changes. 
      ===============================================================*/
    
    shuffle($operators);
    $expression = $second_num.$operators[0].$first_num;
    /*
        operation result is stored in $session_var
    */
    eval("\$session_var=".$second_num.$operators[0].$first_num.";");
    /* 
        save the operation result in session to make verifications
    */
    $_SESSION['security_number'] = $session_var;
    /*
        start the captcha image
    */
    $img = imagecreate( $captcha_w, $captcha_h );
    /*
        Some colors. Text is $black, background is $white, grid is $grey
    */
    $black = imagecolorallocate($img,0,0,0);
    $white = imagecolorallocate($img,255,255,255);
    $grey = imagecolorallocate($img,215,215,215);
    /*
        make the background white
    */
    imagefill( $img, 0, 0, $white );    
    /* the background grid lines - vertical lines */
    for ($t = $bg_size; $t<$captcha_w; $t+=$bg_size){
        imageline($img, $t, 0, $t, $captcha_h, $grey);
    }
    /* background grid - horizontal lines */
    for ($t = $bg_size; $t<$captcha_h; $t+=$bg_size){
        imageline($img, 0, $t, $captcha_w, $t, $grey);
    }
    
    /* 
        this determinates the available space for each operation element 
        it's used to position each element on the image so that they don't overlap
    */
    $item_space = $captcha_w/3;
    
    /* first number */
    imagettftext(
        $img,
        rand(
            $min_font_size,
            $max_font_size
        ),
        rand( -$angle , $angle ),
        rand( 10, $item_space-20 ),
        rand( 25, $captcha_h-25 ),
        $black,
        $font_path,
        $second_num);
    
    /* operator */
    imagettftext(
        $img,
        rand(
            $min_font_size,
            $max_font_size
        ),
        rand( -$angle, $angle ),
        rand( $item_space, 2*$item_space-20 ),
        rand( 25, $captcha_h-25 ),
        $black,
        $font_path,
        $operators[0]);
    
    /* second number */
    imagettftext(
        $img,
        rand(
            $min_font_size,
            $max_font_size
        ),
        rand( -$angle, $angle ),
        rand( 2*$item_space, 3*$item_space-20),
        rand( 25, $captcha_h-25 ),
        $black,
        $font_path,
        $first_num);
        
    /* image is .jpg */
    header("Content-type:image/jpeg");
    /* name is secure.jpg */
    header("Content-Disposition:inline ; filename=secure.jpg");
    /* output image */
    imagejpeg($img);

isset() returns a boolean
http://php.net/manual/en/function.isset.php
but it looks like $_SESSION['security_number'] is not a boolean

That’s what I meant, I figured the opening of that if() wasn’t correct. Perhaps it should read more like

    // Check for a security number:
    if(isset($_POST['secure'])) {
        $secure = $_POST['secure'];
        if ($secure == $_SESSION['security_number']) {
          // do whatever you do for it being correct
          } else {
          // incorrect
        }
    } else {        
        echo '<p class="error">Va rugam verificati codul de validare!</p>';
    }

Droopsnoot I changed what you said and now I get this error in the top of contact :smile:

Undefined index: security_number 

This is how I did it:

 if($fn && $ln && $email && $mesaj) {  // If everything's OK...
    
        // Check for a security number:
        if(isset($_POST['secure'])) {
            $secure = $_POST['secure'];
            if ($secure == $_SESSION['security_number']) {
              // do whatever you do for it being correct
              // Create the body:
                $body = " DATE PERSONALE \n\n 
                        Nume: $ln \n 
                        Prenume: $fn \n  
                        Email: $email \n\n 
                        MESAJ \n $mesaj \n ";
        
                // Make it no longer than 100 characters long:
                $body = wordwrap($body, 100);
            
                // Send the email:
                mail('@yahoo.com', 'Contact Form Submission', $body, "From:$email");
        
                // Print a message:
                echo '<p><em>Va multumim ca ne-ati contactat. O sa va raspundem cat mai repede posibil.</em></p>';
              } else {
                  // incorrect
                  echo '<p class="error">Codul de validare este incorect!</p>';
            }
        } else {        
            echo '<p class="error">Va rugam verificati codul de validare!</p>';
        }                    
                            
            
            
                
            
        
    } else { // If one of the data tests failed.
        echo '<p class="error">Va rugam sa incercati din nou.</p>';
    }

OK, that means that the session variable doesn’t exist for some reason.

Did you put session_start() at the beginning of the script?

Yes I put session_start(), but it looks that is not that problem. I still search.

Well if you have session_start on all relative pages BEFORE headers have been sent, then let’s print session to see what it contains by adding this to your page.

echo "<pre>";
print_r($_SESSION);    
echo "</pre>";

By the way.
You site is trying to force me to open a file called tag1.php
Maybe you have a problem with your includes or something being sent which is preventing session_start.

I have session_start() in that page that makes the security_number and in the header, that is included on contact page.
I don’t know any page called tag1.php. The image captcha is not made by me:

/**
     * @link http://www.php-help.ro
     * 
     * This script is provided as-is, with no guarantees.
     */
    
    /* 
        if you set the session in some configuration or initialization file with
        session id, delete session_start and make a require('init_file.php');
    */

I replaced the session_start() with init_file.php, but nothing happens, because I don’t find in the captcha folder that file. I guess I have to try a diff one.

Looks like even with a diff captcha the session doesn’t work. I have the session_start() in header and is included in contact page from a diff folder:
include(‘folder/header.php’);
In the header the only php code is:

// Start output buffering:
ob_start();
// Initialize a session:
session_start();

if (!isset($page_title)) {

I don’t know why captcha doesn’t work.

Just to be clear session_start(); must be called before ANYTHING is sent to browser. Even a space before <?php would send something to browser.

<?php
session_start(); 
?>
<html>
etc

Just running a little test page, you can see that your session security number is being set, so the problem seems to be session_start.

testpage

<?php
session_start(); 
?>
<html>
<body>
<?php
echo "<pre>";
print_r($_SESSION);    
echo "</pre>";
/*===============================================================
        General captcha settings
      ===============================================================*/
    // captcha width
    $captcha_w = 205;
    // captcha height
    $captcha_h = 50;
    // minimum font size; each operation element changes size
    $min_font_size = 12;
    // maximum font size
    $max_font_size = 18;
    // rotation angle
    $angle = 20;
    // background grid size
    $bg_size = 13;
    // path to font - needed to display the operation elements
    $font_path = '../library/fonts/courbd.ttf';
    // array of possible operators
    $operators=array('+','-','*');
    // first number random value; keep it lower than $second_num
    $first_num = rand(1,5);
    // second number random value
    $second_num = rand(6,11);
        
    /*===============================================================
        From here on you may leave the code intact unless you want
        or need to make it specific changes. 
      ===============================================================*/
    
    shuffle($operators);
    $expression = $second_num.$operators[0].$first_num;
    /*
        operation result is stored in $session_var
    */
    eval("\$session_var=".$second_num.$operators[0].$first_num.";");
    /* 
        save the operation result in session to make verifications
    */
    echo $session_var;
    $_SESSION['security_number'] = $session_var;
?>
</body>
</html>

Thank you very much Drummin, now works :smile:. That was one of the problem. The second one was that I forgot to put the name on the form tag :smile:

Well GREAT!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.