this is my first time in using recaptcha on my website.
I'm using PHP API to validate the recaptcha, it keeps saying invalid-request-cookie
I found out on different forum that www.example.com is different with example.com, so I register my site again without www , but still it is not working..
When I verify the recaptcha_response_field and recaptcha_challenge_field the values are correct.
here is the captcha checker:
require_once(recaptchalib.php');
$publickey = "not displayed"; //for security
$privatekey = "not displayed"; //for security
$error = null;
if( $_POST ) {
$arr = array('a' => $_POST['task'], 'b' => $_POST['recaptcha_challenge_field'], 'c' => $_POST['recaptcha_response_field']);
if( trim($arr['a']) == 'captcha' ) {
$resp = null;
$error = null;
$captcha_result = 'success';
$resp = recaptcha_check_answer( $privatekey, $_SERVER["REMOTE_ADDR"], $arr['b'], $arr['c'] );
if( $resp->error ){
$captcha_result = 'fail';
}
echo $captcha_result;
}
}
here is the HTML code:
<div id="captcha-div">
<script type="text/javascript">
var RecaptchaOptions = {
tabindex: 1,
theme: 'custom',
custom_theme_widget: 'recaptcha_widget'
};
</script>
<div id="recaptcha_widget" style="display:none"><div id="recaptcha_image" style="width: 200px; height: 57px; "></div>
<?php echo recaptcha_get_html($publickey, $error); ?>
<div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect. Try Again.</div>
<span class="recaptcha_only_if_audio">Type what you hear</span>
<input type="text" id="recaptcha_response_field" name="recaptcha_response_field">
<div class="recaptcha_only_if_audio">Kumuha ng larawang CAPTCHA</div>
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6Le_X88SAAAAAAH3NEbkIr3w75SEQnQYwl96Y7f0"></script>
<noscript><iframe src="http://www.google.com/recaptcha/api/noscript?k=6Le_X88SAAAAAAH3NEbkIr3w75SEQnQYwl96Y7f0" height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"></noscript></div>
<script type="text/javascript">
window.onload = function() {
Recaptcha.focus_response_field();
}
</script>
<p id="captcha-error" style="color:red; font-weight:bold;"></p>
</div>
<div><a id="captcha-refresh" href="javascript:Recaptcha.reload()"></a></div>
<div class="recaptcha_only_if_image"><a id="captcha-audio" href="javascript:Recaptcha.switch_type('audio')"></a></div>
<div><a id="captcha-help" href="javascript:Recaptcha.showhelp()"></a></div>
<div id="circle-submit"></div>
can anyone help me out with this issue?
Thanks,
Justin
As reCAPTCHA Support says:
No, this will not result in the invalid domain. What this means is that you are not submitting the recaptcha_challenge_field to the server correctly.
So make sure you rendering the form with recapcha corectly. Check out this link.
Related
I have previously used reCaptcha v1 and all was good until the Google changes a few years ago. I've now been asked to update a site, and am having some problems even with a simple bit of test code. The example below is a single index.php page, which traps for 'POST' when a form is submitted.
The reCaptch tick box appears, and allows a tick, but when the form is submitted I only get the 'Check the reCAPTCHA box' response. It looks like '$captcha=$_POST['g-recaptcha-response'];' is 'blank'. I am using the correct codes, and am getting stats on the reCaptcha admin page, but it is also reporting:
We detected that your site isn't verifying reCAPTCHA solutions. This is required for the proper use of reCAPTCHA on your site. Please see our developer site for more information.
What am I missing to verify?
<head>
<title>Test Contact Form</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
echo "submit detected..<br>";
$full_name;$email;$subject;$message;$captcha;
if(isset($_POST['full_name'])){
$full_name=$_POST['full_name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['subject'])){
$subject=$_POST['subject'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo 'Check the reCAPTCHA box.';
echo $full_name . "<br>";
echo $email . "<br>";
echo $subject . "<br>";
echo $captcha . "<br>";
exit;
}
$secretKey = "6LemhA8aFAKEDRSKVHsecretVzN7Uv1BVQnpS-LwbjOo";
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?".$secretKey."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if($response.success==false)
{
echo 'You are a robot!';
}else
{
echo "I'd be sending an email to " . $email . "<br>";
echo "because the secret key" . $secretKey . "<br>";
echo "and the response " . $captcha . "<br>";
echo "matched.";
}
} ELSE {
?>
<div class="contact-form">
<h3>Send me your message v1</h3>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div class="text-fields">
<span>Full Name *:</span>
<input name="full_name" type="text" class="text" value="Your Name">
</div>
<div class="text-fields">
<span>E-mail *:</span>
<input name="email" type="text" class="text" value="user#domain.com">
</div>
<div class="clearfix"> </div>
</div>
<div class="subject-field">
<span>Subject *:</span>
<input name="subject" type="text" class="text" value="Your Subject">
</div>
<div class="message-field">
<span>Message *:</span>
<textarea name="message"> </textarea>
</div>
<div class="g-recaptcha" data-sitekey="6LemhA8aFAKEJnoerEbOVLWEkeyYO3CcPo-HEIymP"></div>
<input type="submit" name="submit" value="Send" />
</form>
</div>
<?php } ?>
</body>
</html>
Captcha v2 Returns JSON Data (As seen on Official site) You should Decode json and then validate it.
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => 'YOUR_SECRET',
'response' => $_POST["g-recaptcha-response"]
);
$options = array(
'http' => array (
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$verify = file_get_contents($url, false, $context);
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<p>You are a bot! Go away!</p>";
} else if ($captcha_success->success==true) {
echo "<p>You are not not a bot!</p>";
}
there is also one problem in your code in " if($response.success==false)" you should write it as "if($response->success==false)"
I will comment after checking with your secrete id (Delete it afterword)
I suspect it's because you have an extra </div> after <div class="clearfix"> </div> – If you remove it, your code will probably work.
The extra closing div tag makes the browser believe that you're closing <div class="contact-form"> and since the <form> tag is inside of that, it tries fix your HTML and close that as well. However, that means that the remaining fields (subject, message) and reCAPTCHA are placed outside the <form>. reCAPTCHA only sets g-recaptcha-response if it's actually inside a <form>, no matter if the user successfully completes it or not.
An additional adjustment
You also need to decode the JSON returned from https://www.google.com/recaptcha/api/siteverify like so:
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?".$secretKey."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response["success"]==false)
<html>
<head>
<!-- SCRIPTS -->
<script type="text/javascript" src="scripts/controller.js"></script>
<!-- STYLES -->
<link href="styles/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
$errUrl = $videoId = "";
$start = $end = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
if (isset($_POST["yt_url"])) {
echo "hello2";
$videoId = youtube_parser($_POST['yt_url']);
}
if (!$videoId) {
$errUrl = "URL is not valid!";
$videoId = "";
} else {
$errUrl = "";
}
//$start = $_POST['startH'] * 3600 + $_POST['startM'] * 60 + $_POST['startS'] * 1;
//$end = $_POST['endH'] * 3600 + $_POST['endM'] * 60 + $_POST['endS'] * 1;
}
function youtube_parser($url) {
$regExp = '/^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/';
$match = preg_match($regExp, $url, $matches);
return ($match && strlen($matches[5]) === 11)? $matches[5] : false;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="left">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<span class="error">* <?php echo $errUrl; ?></span><br>
URL: <input type="text" name="yt_url">
<br><br>
Start Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="start_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="start_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="start_s">
<br><br>
End Time:<br>
<span class="label">Hour: </span><input value="0" type="number" name="end_h"><br>
<span class="label">Minute: </span><input value="0" type="number" name="end_m"><br>
<span class="label">Second: </span><input value="0" type="number" name="end_s">
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
<div class="player"><?php
if (isset($videoId) && !empty($videoId)) {
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/$videoId?start=$start&end=$end" frameborder="0" allowfullscreen></iframe>';
}
?></div>
</body>
</html>
The above is what I have so far. I am attempting to learn php, and I have been working through the tutorials on w3schools I got to the part about working with forms, and none of the information is being passed in the $_POST array, I have set names for all of my DOM controls. Any insight would be greatly appreciated! I have a feeling it my have something to do with my PHP setup as even the provided example doesn't work.
Additional Information:
Web server running through Intellij PHPStorm.
php version is 7.0.9
Your code looks valid and when I tried it it shows expected output from $_POST array:
So it looks like you got problems with environment you are testing it on.
BTW <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
is wrong. Aside from spaghetti code, you should not use htmlspecialchars() here but urlencode()
(yet I'd use nothing _SERVER['PHP_SELF'] cannot be spoofed by client).
Also as #CarlJan suggested you may want to use isset($_POST['submit']) to check if your form was submitted as this will condition will only be true if your submit button is sent via POST. For now you are checking if this is POST request (in general) but it is not the same as it can be post from other form, or triggered by hand.
I have a ecommerce page where I am using stripe api. Once the payment is successful I want to redirect to the checkoutproc.php after updating the DB. But after clicking submit the page remain on the same page. When I try this on my local host it works perfectly fine but doesnt work when its live. The header is at the bottom of the checkout.php file given here-
<html>
<head>
<title>UNSQ</title>
<link rel="stylesheet" type="text/css" href="css/styling.css">
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<div class="logo" >
<img src=css/images/unsquaringlogo.png height="180" width="700">
</div>
<div class="container">
<h2>Register</h2>
<form action="" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input type="text" size="4" data-stripe="exp-year"/>
</div>
<button type="submit" >Submit Payment</button>
</form>
</div>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('mykey');
// ...
jQuery(function($) {
$('#payment-form').submit(function(event) {
console.log("this is 1");
var $form = $(this);
console.log($form);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
console.log("this is 2");
Stripe.card.createToken($form, stripeResponseHandler);
console.log("this is 3");
// Prevent the form from submitting with the default action
return false;
});
});
</script>
<script>
function stripeResponseHandler(status, response) {
console.log("this is 5");
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
$form.find('.payment-errors').text("success");
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
</script>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
require_once('stripe-php/init.php');
\Stripe\Stripe::setApiKey("mykey");
// Get the credit card details submitted by the form
$token = $_POST['stripeToken'];
// Create the charge on Stripe's servers - this will charge the user's card
try {
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "usd",
"source" => $token,
"description" => "payinguser#example.com")
);
include('config.php');
$sql="insert into login (email,name,password)values('$_GET[email]','$_GET[username]','$_GET[password]')";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
// ***************THIS IS HEADER WHERe I REDIRECT*******
header('Location:checkoutproc.php');
} catch(\Stripe\Error\Card $e) {
// The card has been declined
}
}
} else {
$errors['token'] = 'The order cannot be processed. You have not been charged. Please confirm that you have JavaScript enabled and try again.';
}
?>
</body>
</html>
This is how the *checkoutproc.php* looks
<?php
print "<h1>you have registered sucessfully</h1>";
print "<a href='index.php'>go to login page</a>";
?>
This how the config.php looks like
<?php
$servername = "localhost";
$username = "*****";
$password = ****;
$dbname='unsq';
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully !!";
?>
I'm trying to add reCaptcha to my registration page, but i cant seem to get it to work, it keeps displaying the message that the data was entered incorrectly, the code is below:
<div align="center">
<?PHP
if (isset($_POST['submit']))
{
$username = $_POST["username"];
$password = $_POST["password"];
$password1 = $_POST["password1"];
if(empty($username)) die(print '<script> alert ("Enter Username"); window.location="registration.php"; </script>');
if(empty($password)) die(print '<script> alert ("Enter Password"); window.location="registration.php"; </script>');
if($password != $password1) die(print '<script> alert ("Password doesn\'t match"); window.location="registration.php"; </script>');
require_once('recaptchalib.php'); // reCAPTCHA Library
$privkey = "6Ld27usSAAAAAKiYor8lnBs9fb6HOd1IK5JnTCyL"; // Private API Key
$verify = recaptcha_check_answer($privkey, $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if ($verify!=is_valid) {
echo "You did not enter the correct Captcha. Please try again.";
}
else {
$file = file_get_contents("data.txt");
$string = "$username||$password";
if(!strstr($file, "$string"))
{
$myFile = "data.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "$username||$password\n";
fwrite($fh, $stringData);
print '<script> alert ("Registration Complete"); window.location="index.php"; </script>';
fclose($fh);
}
else
{
echo "Sorry the username: <b>$username</b> is already registered. Please use diferent username.";
}
}
}
?>
</div>
<!doctype html>
<html>
<head>
<title>Registration</title>
</head>
<body>
<div id="container" style="width:500px; height:500px; border: 2px solid black; margin:auto">
<?php include "header.php"; ?>
<div id="content" style="background-color:#EEEEEE; width:500px; height:400px; float: left">
<br>
<form align="center" method="post" action="registration.php" >
Username:
<input type="text" name="username" />
<br/>
<br/>
Password:
<input type="password" name="password" />
<br/>
<br/>
Confirm:
<input type="password" name="password1" />
<br/>
<br/>
<?php
require_once('recaptchalib.php'); // reCAPTCHA Library
$pubkey = "6Ld27usSAAAAAB9Zq67L28CqywwEn9RZ_7bFthm7"; // Public API Key
echo recaptcha_get_html($pubkey); // Display reCAPTCHA
?>
<input type="submit" value="Register" name="submit" />
</form>
</div>
<?php include "footer.php"; ?>
</div>
</body>
</html>
I have a feeling that my problem is in ($verify!=is_valid) but i am not sure. Would appreciate any help.
Per the docs found here, it looks like you're not using the return value of recaptcha_check_answer() properly:
recaptcha_check_answer returns an object that represents whether the
user successfully completed the challenge.
If $resp->is_valid is true then the captcha challenge was correctly completed and you should
continue with form processing.
Instead of $verify != is_valid, you should use the is_valid value on the returned object:
if ($verify->is_valid) {
echo "You did not enter the correct Captcha. Please try again.";
} else {
...
I have created a contact form using labels as a type of place holder, putting them behind the input box with a transparent background then making background white on :focus and setting the background white when value of input is > 0.
I have recently incorporated the necessary PHP into my form which has destroyed my styling. I have recovered it slightly but don't understand why the inputs are a few pixels too long. It changes the styling as soon as I put the PHP above the doctype declaration.
I do not know what to do about the page's label showing through on page refresh. [Have a look][1] and see what you think. How can I get it working smoothly?
[Here is a JSFiddle showing my contact form styling][2].
Here is my php
<?php
if (empty($_POST) === false){
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) === true) {
$errors[] = 'Name, email and message are required!';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Invalid email address';
}
if (ctype_alpha($name) === false) {
$errors[] = 'Name must contain letters only';
}
}
if (empty($errors) === true) {
mail('mailmattysmith#gmail.com', 'Contact form', $message, 'From: ' . $email);
header('Location: index.php?sent');
exit();
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Matthew Smith | Contact</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
#contact_btn{
border-bottom: 5px solid #0af !important;
}
</style>
</head>
<body>
<?php
include("header.php");
?>
<div id="wrapper">
<img class="click_contact" id="logo" src="img/logo1.png">
<br><p id="contact_me" class="quote">Get In touch</p>
<div id="contact_form">
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting me</p>';
} else {
if (empty($errors) === false) {
echo '<ul>';
foreach ($errors as $error) {
echo '<li>', $error, '</li>';
}
echo '</ul>';
}
?>
<form action="" method="post" >
<div class="input_wrap" id="first">
<input type="text" name="name" id="name" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?>>
<label for="name">Name</label>
</div>
<div class="input_wrap">
<input type="text" name="email" id="email" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?>>
<label for="email">Email</label><br>
</div>
<div class="input_wrap">
<input>
<label>Subject</label>
</div>
<div class="input_wrap" id="last">
<textarea name="message" id="message"><?php if (isset($_POST['message']) === true) { echo strip_tags($_POST['message']), ''; } ?></textarea>
<label for="message">Message</label>
</div>
<input type="submit" id="send" value="Send">
</form>
<?php
}
?>
</div>
<div id="footer"><p>© Matt Smith <?php echo date('Y'); ?></p></div>
</div>
<script type="text/javascript">
$('#logo').click(function(){
$('html, body').animate({
scrollTop: $(".quote").offset().top
}, 1000);
});
$('input, textarea').on('keyup', function() {
var $this = $(this);
if($(this).val().length > 0) {
$this.css({backgroundColor: '#fff'});
} else {
$this.css({backgroundColor: 'transparent'});
}
});
</script>
</body>
</html>
{[1]: http://www.dominichook.co.uk/matthew/contact.php
{[2]: http://jsfiddle.net/tUnc4/
The problem with your contact form is not the PHP, but actually the way you've coded your labels for the fields. I see that the form submits, and then you do your verification in PHP, then if there is a problem it returns the form with the current values set using the value attribute. This is all fine, but you need a way of removing the labels or just use the placeholder attribute.
Here's a jsfiddle using the placeholder attribute.
You should consider using the placeholder attribute instead of your overly complex solution.
For example:
<label for="email">Email</label>
<input type="email" placeholder="you#example.com" name="email" id="email" />
Browser that do not support this attribute will ignore it. You may simulate the effect for older browsers with JavaScript (for example, Simple-Placeholder).