On my registration page, I have a security question that the user has to answer. It works great and have stopped spam bots.
Here is the script (very lightweight):
add_action( 'register_form', 'add_register_field' );
function add_register_field() { ?>
<p>
<label><?php _e('What is the name of the ship in the TV show Firefly?') ?><br />
<input type="text" name="user_proof" id="user_proof" class="input" size="25" tabindex="20" /></label>
</p>
<?php }
add_action( 'register_post', 'add_register_field_validate', 10, 3 );
function add_register_field_validate( $sanitized_user_login, $user_email, $errors) {
if (!isset($_POST[ 'user_proof' ]) || empty($_POST[ 'user_proof' ])) {
return $errors->add( 'proofempty', '<strong>ERROR</strong>: You did not answer the proof-of-humanship question.' );
} elseif ( strtolower( $_POST[ 'user_proof' ] ) != 'serenity' ) {
return $errors->add( 'prooffail', '<strong>ERROR</strong>: You did not answer the proof-of-humanship question correctly.' );
}
}
And here is a picture of how it looks:
So the answer the user has to input is serenity
. The problem is that some users type it as Serenity
, or add a random blank space somewhere.
My question is, how can I make it so that the value they input gets converted to lowercase and any blank spaces are removed prior to checking if the value is correct? This way, if they input Ser enItY
, it will be fine.
Use str_replace(' ', '', $string)
to remove white-spaces; trim($string)
to remove any other "junk" around input; strtolower($string)
to get string in lowercase. To compare string use strcmp($string, $string1)
In the end you get:
if (strcmp('serenity', strtolower(str_replace(' ', '', trim($_POST['user_proof'])))) == 0)
In your code:
function add_register_field_validate($sanitized_user_login, $user_email, $errors) {
if (empty($_POST['user_proof'])) {
return $errors->add('proofempty', '<strong>ERROR</strong>: You did not answer the proof-of-humanship question.' );
} elseif (strcmp('serenity', strtolower(str_replace(' ', '', trim($_POST['user_proof'])))) != 0) {
return $errors->add('prooffail', '<strong>ERROR</strong>: You did not answer the proof-of-humanship question correctly.' );
}
}