检查数据库中是否存在电子邮件地址,如果不提供警报则验证验证码是否正确,并且不要将数据保存在数据库中

时间:2015-07-23 09:29:44

标签: php mysql

我写了一个表格的代码,其中我添加了两个验证,第一个是通过电子邮件,第二个是通过电子邮件。当用户输入已存在于数据库中的电子邮件地址时,它将显示错误。我遇到的问题是,当用户输入新的电子邮件地址和错误的验证码时,它会显示错误,但同时也会将其保存到数据库中。这里给出了完整的代码

<?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 个答案:

答案 0 :(得分:0)

这里有几条评论。首先,也许是最重要的,您正在使用mysql_*函数,这些函数已弃用且不再维护。您应该认真考虑转换为MySQLi或PDO,它已准备好语句(protects you against SQL-inection)。 mysql_* 不良做法

此外,您在代码中混合使用变量名称。您正在使用$_POST['finam']$_POST['finame'],我认为它们是同一个。小心你的名字!

您正在以纯文本格式插入密码 - 这也是一个安全问题!你应该真正哈希你的密码,以便它永远不会以纯文本形式存储(如果黑客访问你的数据库)。

至于您的问题:您正在or - 语句中使用一系列if - 运算符插入数据库。这意味着只要一个返回TRUE,它就会运行查询并插入电子邮件。

我不确定你是如何进行CAPTCHA验证的,但我认为这段代码会更有效。

<?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;
    }
}

?>

正如您所看到的,我还更新了您的INSERT - 查询,这有点混乱。