RECAPTCHA wird als erstes gecheckt ?

Code46

Erfahrenes Mitglied
Hi,

in meinem Formula habe ich Eingabefelder wie Username,email, password und zum Schluss den Recaptcha check.
Wenn ich den Button Register drücke, dann checkt er sofort den Wert im Recaptcha,jedoch möchte ich das zuerst die Felder überprüft werden. Wie kann ich das machen?

PHP:
<?php
include 'dbc.php';
$errors =array();

//If the Submit button is pressed
if (isset($_POST['doRegister']))
{

/********************* RECAPTCHA CHECK *******************************
This code checks and validates recaptcha
****************************************************************/
 require_once('recaptchalib.php');
     
      $resp = recaptcha_check_answer ($privatekey,
                                      $_SERVER["REMOTE_ADDR"],
                                      $_POST["recaptcha_challenge_field"],
                                      $_POST["recaptcha_response_field"]);

      if (!$resp->is_valid) {
        die ("<h3>Image Verification failed!. Go back and try again.</h3>" .
             "(reCAPTCHA said: " . $resp->error . ")");			
      }
/**********************************************************************/


/***************** Setting Variabls ***********************************/

// Automatically collects the hostname or domain  like example.com
$host  = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$path   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');

// Generates activation code simple 4 digit number
$activ_code = rand(1000,9999);

//Variables to get the values form the Form
$usr_email = $_POST['usr_email'];
$user_name = $_POST['user_name'];
$user_postcode = $_POST['user_postcode'];
$user_ip = $_SERVER['REMOTE_ADDR'];
$password = md5($_POST['pwd']);
$pwd = $_POST['pwd'];

/**********************************************************************/


// Checking Inputs
	if(empty($_POST['user_name']))
	{
		$errors[] ='Please enter your username';
	}
	else if(username_exists($_POST['user_name'])==true)
	{
		$errors[] ='This username is already registered with us. <a href="register.php">Login?</a> ';
	}
	else if(empty($_POST['usr_email']))
	{
		$errors[] ='Please enter your email address';
	}
	else if(valid_email($_POST['usr_email'])==false)
	{
		$errors[] ='Invalid email address';
	}
		else if(email_exists($_POST['usr_email'])==true)
	{
		$errors[] ='This email is alrady registered with us. <a href="register.php">Login?</a>';
	}
	else if(empty($_POST['user_postcode']))
	{
		$errors[] ='Please enter your Postcode';
	}
	else if(PostcodeValidation($_POST['user_postcode'])==false)
	{
		$errors[] ='Invalid Postcode';
	}
	else if(empty($_POST['pwd']))
	{
		$errors[] ='Please enter a password';
	}
	else if(strlen($_POST['pwd']) <5)
	{
		$errors[] ='Password must be minimum five characters';
	}
	else if($_POST['pwd']!= $_POST['pwd2'] )
	{
		$errors[] ='Password does not match';
	}


if (empty($errors))
	{
// Inserts the Values into the DB
	$sql_insert = "INSERT into `users`
  			(`user_name`,`user_email`,`pwd`,`postcode`,`date`,`users_ip`,`activation_code`
			)
		    VALUES
		    ('$user_name','$usr_email','$password','$user_postcode',now(),'$user_ip','$activ_code'
			)
			";
//If the Values are correct it will save it into the DB otherwise it will give an error			
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());

$message = 
"Dear $user_name \n
Thank you for registering with us. Here are your login details...\n

User ID: $user_name
Email: $usr_email \n 
Password: $pwd \n
Activation Code: $activ_code \n

*****ACTIVATION LINK*****\n
http://$host$path/activate.php?user=$user_name&activ_code=$activ_code

Thank You

Administrator
$host_upper
______________________________________________________
THIS IS AN AUTOMATED RESPONSE. 
***DO NOT RESPOND TO THIS EMAIL****
";

	mail($usr_email, "Login Details", $message,
    "From: \"Member Registration\" <auto-reply@$host>\r\n" .
     "X-Mailer: PHP/" . phpversion());

  header("Location: thankyou.php");  
  exit();


	}

}

 
function PostcodeValidation($postcode)
    {
    $postcode = strtoupper(str_replace(' ', '', $postcode));
    if(preg_match("/^[A-Z]{1,2}[0-9]{2,3}[A-Z]{2}$/",$postcode) || preg_match("/^[A-Z]{1,2}[0-9]{1}[A-Z]{1}[0-9]{1}[A-Z]{2}$/",$postcode) || preg_match("/^GIR0[A-Z]{2}$/",$postcode))
    return true;
    else
    return false;
    }

//CHECKS IF THIS IS A VALID EMAIL ADRESS
function valid_email($email)
{
	 $email = mysql_real_escape_string($email);
	 if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $email)) return true;
     else return false;
}
//CHECKS IF THE EMAIL ALREADY EXISTS IN DATABASE
function email_exists($usr_email)
{
		$email = mysql_real_escape_string($usr_email);
		$count = mysql_num_rows(mysql_query("SELECT * FROM users WHERE user_email ='$usr_email' "));
		if($count !=0){return true;}else {return false;}
}
//CHECKS IF THE USERNAME ALREADY EXISTS IN DATABASE
function username_exists($user_name)
{
		$username = mysql_real_escape_string($user_name);
		$count = mysql_num_rows(mysql_query("SELECT * FROM users WHERE user_name ='$user_name' "));
		if($count !=0){return true;}else {return false;}
}



?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Free Registration/Signup Form</title>
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">

  <script>
  $(document).ready(function(){
    $.validator.addMethod("username", function(value, element) {
        return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
    }, "Username must contain only letters, numbers, or underscore.");

    $("#regForm").validate();
  });
  </script>


</head>

<body>
<table width="100%" border="0" cellspacing="0" cellpadding="5" class="main">
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  <tr> 
    <td width="160" valign="top"><p>&nbsp;</p>
      <p>&nbsp; </p>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p></td>
    <td width="732" valign="top">
      <h3 class="titlehdr">Free Registration / Signup</h3>
      <p>Please register a free account, before you can start posting your ads. 
        Registration is quick and free! Please note that fields marked <span class="required">*</span> 
        are required.</p>
	  <br>
      <form action="register.php" method="post" name="regForm" id="regForm" >
       <fieldset >
					<legend><strong>Create Account</strong></legend>

		<table width="95%" border="0" cellpadding="3" cellspacing="3" class="forms">
			<div id="msg_area"><span id ="error">*<?php foreach($errors as $error){echo "{$error}";}?></span></div><br>
            <td>Username<span class="required"><font color="#CC0000">*</font></span></td>
            <td><input name="user_name" type="text" id="user_name" class="required username" minlength="5" value ="<?php if(isset($_POST['user_name'])) echo htmlentities($_POST['user_name'])?>" onblur ="validateUsername(this.value)"> 
			    <span style="color:red; font: bold 12px verdana; " id="checkid" ></span> 
            </td>
          </tr>
		  <tr> 
            <td>Your Email<span class="required"><font color="#CC0000">*</font></span> 
            </td>
            <td><input name="usr_email" type="text" id="usr_email3" class="required email" value ="<?php if(isset($_POST['usr_email'])) echo htmlentities($_POST['usr_email'])?>" onblur ="validateUsername(this.value)"> 
              <span class="example">** Valid email please [example: myemail@email.com]</span>
			  </td>
          </tr>
		  <tr> 
            <td>Your Postcode<span class="required"><font color="#CC0000">*</font></span> 
            </td>
            <td><input name="user_postcode" type="text" id="usr_postcode" class="required postcode" value ="<?php if(isset($_POST['user_postcode'])) echo htmlentities($_POST['user_postcode'])?>" onblur ="validateUsername(this.value)"> 
              <span class="example">** Valid Postcode please [example: SE8 4AA]</span></td>
          </tr>
          <tr> 
            <td>Password<span class="required"><font color="#CC0000">*</font></span> 
            </td>
            <td><input name="pwd" type="password" class="required password" minlength="5" id="pwd" value ="<?php if(isset($_POST['pwd'])) echo htmlentities($_POST['pwd'])?>" onblur ="validateUsername(this.value)"> 
              <span class="example">** 5 chars minimum..</span></td>
          </tr>
          <tr> 
            <td>Retype Password<span class="required"><font color="#CC0000">*</font></span> 
            </td>
            <td><input name="pwd2"  id="pwd2" class="required password" type="password" minlength="5" equalto="#pwd" value ="<?php if(isset($_POST['pwd2'])) echo htmlentities($_POST['pwd2'])?>" onblur ="validateUsername(this.value)" ></td>
          </tr>
		<tr> 
            <td width="22%"><strong>Image Verification </strong></td>
            <td width="78%"> 
              <?php 
			require_once('recaptchalib.php');
			
				echo recaptcha_get_html($publickey);
			?>
            </td>
          </tr>
            <td colspan="2"> <div align="center"> 
                <p><a href="index.html">Home</a><font color="#FF6600"> 
                  |</font> <a href="login.php">Login</a> <font color="#FF6600"> 
                  </font></p>
              </div></td>
          </tr>
        </table>
        <p align="center">
          <input name="doRegister" type="submit" id="doRegister" value="Register">
        </p>
      </form>	   
      </td>
    <td width="196" valign="top">&nbsp;</td>
  </tr>
  <tr> 
    <td colspan="3">&nbsp;</td>
  </tr>
  </fieldset>
</table>


</body>
</html>
 
Zuletzt bearbeitet von einem Moderator:
/********************* RECAPTCHA CHECK *******************************
This code checks and validates recaptcha
****************************************************************/
require_once('recaptchalib.php');

$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);

if (!$resp->is_valid) {
die ("<h3>Image Verification failed!. Go back and try again.</h3>" .
"(reCAPTCHA said: " . $resp->error . ")");
}
/**

Das weiter nach hinten stellen?
 
Dir ist klar das generell alles mit enem Request geprüft wird? Sonst müsstest du über JS gehen. Theoretisch kannst du aber die Feldprüfungen vorher im Skript bearbeiten und dann die Auswertung schon abbrechen, wenn dort fehler sind ;)
 
Wie meinst du es ?

Ich will beides JavaScript und PHP benutzen, was ich auch tuhe.
 
Zuletzt bearbeitet:
item: Warum prüfst du deine Inputs nicht gleich über filter_input_array()

Naja, egal.
Du musst nur die folgenden Zeilen weiter nach unten Rücken. unterhalb des Input-Prüf-teils
PHP:
      if (!$resp->is_valid) {
        die ("<h3>Image Verification failed!. Go back and try again.</h3>" .
             "(reCAPTCHA said: " . $resp->error . ")");         
      }
 
Beispiele gibts auf php.net in der Doku. Wennd u aber neu bist, dann lass es so wies jetzt ist. Ist einfachwer zu verstehen
 
Nochmal eine andere frage, hast du ein gutes beispiel für Login scripts ? Ich habe jetzt mein anmelde formular fertig, muss jetzt nur noch das Login script schreiben
 
Zurück