1

i wrote a code for a form in which i added a two validation first one is through email and second one is through email. when user enter's the email address which already exist in a data base it will show an error. the problem which i faced is that when user enter's a new email address and wrong captcha code than it will show an error but at the same time it will save that into the data base also. Here's the complete code is given

<?php
include('../config/connection.php'); 

//DATABASE INSERT QUERY
if(isset($_POST['submit']))
{
        $finame = $_POST['finame'];
    $email = $_POST['email'];
    $user_message = $_POST['message'];
    $b="SELECT * from form WHERE email='".$_POST['email']."'";

                 $res = mysql_query($b);
            $tot = mysql_fetch_assoc($res);
            if(empty($tot) || empty($_SESSION['6_letters_code'] ) ||
      strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) == 0)
                {


                        $sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
                mysql_query($sel);

                    }   



    //-------------------------------Captcha--------------------
    $your_email ='yourname@your-website.com';// <<=== update to your email address

session_start();
$errors = '';
$finame = '';
$email = '';
$user_message = '';

    ///------------Do Validations-------------


    if(!empty($tot))
    {
        $errors .= "\n Re-enter the captcha code...!!! ";   
        $msg .="Email adreess already exist";
    }
    if(IsInjected($email))
    {
        $errors .= "\n Bad email value!";
    }
    if(empty($_SESSION['6_letters_code'] ) ||
      strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    {

    // strcmp()
        $errors .= "\n The captcha code does not match!";
    }

    if(empty($errors))
    {
        //send the email
        $to = $your_email;
        $subject="New form submission";
        $from = $your_email;
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

        $body = "A user  $name submitted the contact form:\n".
        "Name: $finame\n".
        "Email: $email \n".
        "Message: \n ".
        "$user_message\n".
        "IP: $ip\n";    

        $headers = "From: $from \r\n";
        $headers .= "Reply-To: $visitor_email \r\n";

        mail($to, $subject, $body,$headers);

        header('Location: ../admin/sign-in1.php');
    }
}

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

?>


<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript">
    window.onload = function(){
        new JsDatePick({
            useMode:2,
            target:"inputField",
            dateFormat:"%d-%M-%Y"
            });
    };
            </script>
<title>Form</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'>
<script language="JavaScript" src="scripts/gen_validatorv31.js" type="text/javascript"></script>
</head>

<body>
<div style="width:100%; height:170px; margin:auto;">
    <div class="abc">
    <h1 style="margin:5% 0 0 5%; width:10%; color:#FFF;">Form</h1>
     <!--</form>-->
    <?php 
                    $sel = "select * from home";
                    $a=mysql_query($sel);  
                   $fetch = mysql_fetch_array($a);

                     ?>
            <div class="sample"> <?php echo $fetch['home4'];?></div>
                <div class="main" style="margin:4% 0 0 0;">
                <a href="../index.php" class="navi">Home</a>
                <a href="../index.php" class="navi">About us</a>
                <a href="../index.php" class="navi">Gallery</a>
                <a href="../index.php" class="navi">Contact us</a>
        </div>
    </div>

    </div>
<div style=" width:100%; margin:5% 0 0 0; height:auto;">   
    <div style="margin:auto; width:80%">
        <form method="post" class="w3-container" onSubmit="alert('Thank you. You are registered now input your login id and passwprd to make changes on index and another pages...')" >
            <div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['finam'] ?>" type="text" name="finam"required>
                <label class="w3-label">First-Name</label>
            </div>
            <div class="w3-group">
<input class="w3-input blue-l4" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['lnam'] ?>" type="text" name="lnam"required>
                <label class="w3-label">Last name</label>
            </div>
            <div class="w3-group">
            <input class="w3-input blue-l4" type="text" size="12" readonly id="inputField" value="<?php echo $_POST['dob'] ?>"  name="dob" placeholder="DD/MM/YY"required>

            </div>
            <div class="w3-group">
            <input class="w3-input blue-l4" type="text" pattern="[A-Za-z]{3,}" title="only alphabets" value="<?php echo $_POST['fanam'] ?>" name="fanam"required>
                <label class="w3-label">Father's name</label>
            </div>

           <div class="w3-group">
                  <?php
if(!empty($msg)){
echo "<p class='err'>".nl2br($msg)."</p>";
}
?>
                <input class="w3-input blue-l4"  value="<?php echo $_POST['email'] ?>" type="email" name="email"required>                                                                   
                <label class="w3-label">Email</label>
            </div>
            <div class="w3-group">
                <input class="w3-input blue-l4" type="password" name="passw" required>
                <label class="w3-label">Password</label>
            </div>

            <div class="w3-group">
                <input class="w3-input blue-l4" pattern="[0-9]+" value="<?php echo $_POST['cntn'] ?>"  title="only numeric value" type="text" name="cntn"required>
                <label class="w3-label">Contact no.</label>
           </div>
           <div class="clear"></div>

               <div class="w3-group">

             <select name="str"  class="w3-input blue-l4">
             <option>--Select Stream--</option>
                <?php 
                            $sel = "select * from stream";
          $a=mysql_query($sel);

                           while($fetch = mysql_fetch_array($a))
                           {
                             ?>    
                <option><?php echo $fetch['str']?></option>
                <?php  
                           }
                        ?>

             </select>
                   </div>

            <div class="w3-group">
      <?php
if(!empty($errors)){
echo "<p class='err'>".nl2br($errors)."</p>";
}
?>

               <img src="captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
        <label for='message'>Enter the code above here :</label><br>            

        <input class="w3-input blue-l4" id="6_letters_code" name="6_letters_code" type="text"><br>

        <small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>   </div>

            <button class="w3-btn blue-d1" name="submit" value="submit">Submit</button>

        </form>
    </div>
</div>
<script language='JavaScript' type='text/javascript'>
function refreshCaptcha()
{
    var img = document.images['captchaimg'];
    img.src = img.src.substring(0,img.src.lastIndexOf("?"))+"?rand="+Math.random()*1000;
}
</script>
<div class="foot" style="margin-top:4px;">
    <div  style="margin:2% 0 2% 86%;">
    <a href="http://facebook.com"><img style="margin:0 0 12px 12px;" src="index.jpg" width="30" height="30"/></a>
    <a href="http://twiter.com"><img style="margin:0 0 12px 12px;" src="images1.png" width="30" height="30"/></a>
    <a href="htp://google+.com"><img src="googleplus.png" width="50" height="50"/></a>
    </div>
</div>
</div>
</body>
</html>

1 Answers1

0

Several comments here. First, and maybe the most important, you're using mysql_* functions, which are deprecated and is no longer maintained. You should seriously consider converting to MySQLi or PDO, which has prepared statements (that protects you against SQL-inection). mysql_* is bad practice.

Furthermore, you are mixing variable-names in your code. You're using both $_POST['finam'] and $_POST['finame'], which I assume are one and the same. Be careful with your names!

And you're inserting the password in plain text -- this is also a security issue! You should really hash your password, so that it's never stored in plain text (in case of a hacker accessing your database).

As for your question: You are inserting into the database with a series of or-operators in your if-statement. This means as long as one of them returns TRUE, it'll run the query and insert the email.

I'm not really sure how you do your CAPTCHA-validating, but I think this code will work more as intended.

<?php 
session_start(); 
include('../config/connection.php'); 

//DATABASE INSERT QUERY
if (isset($_POST['submit'])) {
    $finame         = $_POST['finam'];
    $lname          = $_POST['lnam'];
    $dob            = $_POST['dob'];
    $passw          = $_POST['passw'];
    $email          = $_POST['email'];
    $fanam          = $_POST['fanam'];
    $cntn           = $_POST['cntn'];
    $user_message   = $_POST['message'];
    $str            = $_POST['str'];
    $errors         = '';

    ///------------Do Validations-------------
    // Checking if the email exists in the database
    $res = mysql_query("SELECT * FROM form WHERE email=$email");

    // If the number of rows from the result is greater than 0, the email is already in our database
    if (mysql_num_rows($res) > 0) {
        $errors .= "\n Email exists!";
        $emailAvailable = false;
    } else {
        $emailAvailable = true;
    }

    if (!$emailAvailable)) {
        $errors .= "\n Re-enter the captcha code...!!! ";   
        $msg .= "Email adreess already exist";
    }
    if (IsInjected($email)) {
        $errors .= "\n Bad email value!";
        $badEmail = false;
    } else {
        $badEmail = true;
    }

    if (empty($_SESSION['6_letters_code'] ) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0) {
        // strcmp()
        $errors .= "\n The captcha code does not match!";
        $captcha = false;
    } else {
        $captcha = true;
    }

    ///------------If all is well, inserting the email-------------
    if ($emailAvailable && $captcha && $badEmail) {
        // $sel = "insert into ".form." set finam='".$_POST['finam']."',lnam='".$_POST['lnam']."',dob='".$_POST['dob']."',cntn='".$_POST['cntn']."',fanam='".$_POST['fanam']."',str='".$_POST['str']."',email='".$_POST['email']."',passw='".$_POST['passw']."'";
        $sel = "INSERT INTO form (finam, lnam, dob, cntn, fanam, str, email, passw) VALUES ($finame, $lname, $dob, $cntn, $fanam, $str, $email, $passw)";
        mysql_query($sel);
    }

    //-------------------------------Captcha--------------------
    $your_email ='yourname@your-website.com';// <<=== update to your email address

    if(empty($errors)) {
        //send the email
        $to         = $your_email;
        $subject    = "New form submission";
        $from       = $your_email;
        $ip         = $_SERVER['REMOTE_ADDR'];

        $body = "A user  $name submitted the contact form:\n".
        "Name: $finame\n".
        "Email: $email \n".
        "Message: \n ".
        "$user_message\n".
        "IP: $ip\n";    

        $headers = "From: $from \r\n";
        $headers .= "Reply-To: $visitor_email \r\n";

        mail($to, $subject, $body,$headers);

        header('Location: ../admin/sign-in1.php');
    }
}

// Function to validate against any email injection attempts
function IsInjected($str) {
    $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
    $inject = join('|', $injections);
    $inject = "/$inject/i";
    if (preg_match($inject,$str)) {
        return true;
    } else {
        return false;
    }
}

?>

As you can see, I also updated your INSERT-query, it was kind of messy.

Community
  • 1
  • 1
Qirel
  • 25,449
  • 7
  • 45
  • 62
  • I hope you read all the text in my answer above and take it into consideration. Glad I could help! Please make sure to tag the answer as correct if it helped! :) – Qirel Jul 24 '15 at 09:27