Related
I am trying to send notification whenever the database is inserted with new value but i keep getting "error in sending request" repeatedly while trying this code,not able to find what's the problem, I have used server api key as suggested. I have used one form that takes two textboxs which will be directed to the other file above.
<?php
$host='localhost';
$username='';
$pwd="";
$db="";
$con=mysqli_connect($host,$username,$pwd,$db);
if($_SERVER['REQUEST_METHOD']=='POST'){
$full_name = $_POST['full_name'];
$contact_number = $_POST['contact_number'];
//require_once('dbConnect.php');
$sql = "INSERT INTO notification (full_name,contact_number) VALUES (
'$full_name'
'$contact_number')";
$check = "SELECT * from notification where full_name='$full_name' AND contact_number='$contact_number'";
$checkData = mysqli_query($con,$check);
if (mysqli_num_rows($checkData) > 0) {
echo "Request already posted";
}else{
if(mysqli_query($con,$sql)){
$notiTitle = "notification request";
$notiMessage ="by".$full_name;
sendNotification($notiTitle, $notiMessage);
echo "sucessfully added";
}else{
echo "error in sending request";
}
}
}else{
echo 'error';
}
function sendNotification($title, $msg) {
$titlee = $title;
$message = $msg;
$path_to_fcm = 'https://fcm.googleapis.com/fcm/send';
$server_key = "AIz#################################";
$sql = "SELECT app_id FROM user_app_id";
$result = mysqli_query($con,$sql);
// fetch all key of devices
$finalKey=array();
while($row= mysqli_fetch_array($result)){
$finalKey[]=$row['app_id'];
}
$headers = array(
'Authorization:key=' .$server_key,
'Content-Type : application/json');
$fields = array('registration_ids'=>$finalKey, 'notification'=>array('title'=>$title, 'body'=>$message));
$payload = json_encode($fields);
$curl_session = curl_init();
curl_setopt($curl_session, CURLOPT_URL, $path_to_fcm);
curl_setopt($curl_session, CURLOPT_POST, true);
curl_setopt($curl_session, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_session, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
curl_setopt($curl_session, CURLOPT_POSTFIELDS, $payload);
$result = curl_exec($curl_session);
curl_close($curl_session);
echo $result;
mysqli_close($con);
}
<html>
<body>
<form action="init.php" method="post">
Full Name: <input type="text" name="full_name"><br>
Contact No: <input type="text" name="contact_number"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
?>
Can anyone help me on this?
Not sure if it was a typo in your code, but you need to adjust the PHP code - you've wrapped the HTML within the <?php ?> segment.
Try exiting the PHP segment before the HTML starts like below;
?>
<html>
<body>
<form action="init.php" method="post">
Full Name: <input type="text" name="full_name"><br>
Contact No: <input type="text" name="contact_number"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
I created an AMP page for my website, all works fine on my desktop browser, tested and works fine on my mobile, if certain fields are empty or not valid, the submit-error correctly displays the error message, also, on successful submission it correctly displays the submit-success message.
When I submitted the page to Google to cache the amp page, I tested the form once again, this time it isn't displaying the error or success messages. But if the form submission is valid, it will send me an email but not display the success message.
Form html code:
<form action-xhr="posts/submit.php" method="POST" class="contactForm" target="_top">
<fieldset>
<div class="formFieldWrap">
<label class="field-title">Select a product:<span>(required)</span></label>
<div class="select-style full-bottom">
<select name="product">
<option selected="" disabled="">Select a Product</option>
<option value="product1">product 1</option>
<option value="product2">product 2</option>
</select>
</div>
</div>
<div class="formFieldWrap">
<label class="field-title">Full Name:<span>(required)</span></label>
<input type="text" name="fullname" value="" class="contactField" />
</div>
<div class="formFieldWrap">
<label class="field-title">Telephone: <span>(required)</span></label>
<input type="text" name="telephone" value="" class="contactField" />
<div class="formFieldWrap">
<label class="field-title">Email: <span>(required)</span>
</label>
<input type="text" name="email" value="" class="contactField" />
</div>
<input type="hidden" name="ps" value="amp_Homepage">
<div class="formSubmitButtonErrorsWrap contactFormButton">
<input type="submit" class="buttonWrap button bg-teal-dark contactSubmitButton" value="Start my claim" />
</div>
</fieldset>
<div submit-success>
<template type="amp-mustache">
<span class="center-text color-green-dark"><strong>Congratulations {{fullname}}!</strong> You have successfully submitted your claim. You can expect a telephone call from My Claim Solved just to confirm a few details.</span>
</template>
</div>
<div submit-error>
<template type="amp-mustache">
<span class="center-text color-red-light"><strong>Oops!</strong> {{message}}</span>
</template>
</div>
</form>
PHP page:
<?php
$source_origin = trim($_REQUEST['__amp_source_origin']);//Security
if($source_origin != "https://example.com"){
echo "Not allowed origin";
return;
}
header('AMP-Access-Control-Allow-Source-Origin: https://example.com');
header('Content-Type: application/json; charset=UTF-8;');
$start = microtime(true);
$con=mysqli_connect("myip","myuser","mypass","mydb");
$Product = mysqli_real_escape_string($con, $_REQUEST['product']);
$FullName = mysqli_real_escape_string($con, $_REQUEST['fullname']);$FullName = ltrim($FullName);$FullNameMail = mysqli_real_escape_string($con, $_REQUEST['fullname']);
$Telephone = mysqli_real_escape_string($con, $_REQUEST['telephone']);
$Email = mysqli_real_escape_string($con, $_REQUEST['email']);
$Provider = mysqli_real_escape_string($con, $_REQUEST['provider']);
$PageSource = mysqli_real_escape_string($con, $_REQUEST['ps']);
if($Product != 'product1' && $Product != 'product2'){
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must select a product.'));
}elseif(empty($FullName) || strlen($FullName)<3) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter your full name.'));
}elseif (empty($Telephone) || strlen($Telephone)<9) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid telephone number.'));
}elseif (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Status: 400', TRUE, 400);
echo json_encode(array('message'=>'You must enter a valid email address.'));
}else{
// Send Email
$To = "myemail#example.com";
$Message = "bla bla";
$Headers = "From: myemail#example.com";
mail($To, 'subject bla', $Message, $Headers);
echo json_encode(array("product"=>$Product,"fullname"=>$FullName,"telephone"=>$Telephone,"email"=>$IPAddress));
}
?>
just to let you know how it was fixed (thanks to ade for pointing me in the right direction), I amended the headers on the php page to the below:
header("access-control-allow-credentials:true");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("access-control-allow-origin:".$_SERVER['HTTP_ORIGIN']);
header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin");
header("amp-access-control-allow-source-origin:https://".$_SERVER['HTTP_HOST']);
header("Content-Type: application/json");
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 1 year ago.
Here is my code. Don't know why getting this problem. Will really appreciate any help. The error says: “Trying to get property of non-object in C:\xampp\htdocs\registration.php on line 111” I am trying to create an account at registration page and also enabling reCaptcha.
<?php
require_once('includes/settings.php');
?>
<!DOCTYPE html>
<html>
<head>
<title>FirstAide</title>
<link rel="stylesheet" type="text/css" href="css files/loginAndRegistration.css">
<link rel="stylesheet" href="css files/sweetalert.css">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form method="POST" onsubmit="return validate()" /><!--validations for form fields entered js file- validation-v12.js-->
</head>
<body>
<center>
<div>
<h1 class="text">First Aide</h1>
<hr id="line">
<h2 class="text">A Confidentiality Safety Resource for Peace Corps Volunteers</h2>
</div>
<!--form fields for registration-->
<div class="div-reg">
<table class="tables">
<tr>
<th class="text">Username:</th>
<td><input class="input-box" type="text" id="uname" name="uname" placeholder="Enter your username" required/></td>
</tr>
<tr>
<th class="text" style="vertical-align: top">Password:</th>
<td>
<input class="input-box" type="password" id="password" name="password" required/>
<div id="password-validation">
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text" class="text">Password Strength: Very Weak</p>
<ul id="suggestion">
<li>at least one upper case letter</li>
<li>at least one number</li>
<li>at least one special character</li>
<li>minimum 6 characters long</li>
</ul>
</div>
</td>
</tr>
<tr>
<th class="text" style="vertical-align: top">Confirm Password:</th>
<td>
<input class="input-box" type="password" id="confirmpassword" name="confirmpassword" required/>
</td>
<tr>
<th class="text">Host Country:</th>
<td><select id = "host_country" name = "host_country" required></select></td>
</tr>
<tr>
<th class="text">Email:</th>
<td><input class="input-box" type="text" id="email" name="email" placeholder="Enter your email address" required /></td>
</tr>
</table>
<div class="g-recaptcha" data-sitekey="<?php echo $_settings['reCaptcha']['client_key']?>"></div>
</div>
<!--submit button-->
<div class="div-reg">
<input class="button" type="submit" value="Create Account">
<br><br>
<p class="text">Already have an account? Sign in</p><br><br>
<img src="images/secure.png" style="width: 20px; height: 20px;"/>
<div class="text">This is a secure portal</div>
</div>
</center>
<script src="javascripts/passwordStrengthChecker.js"></script>
<script type="text/javascript" src="javascripts/validation-v12.js"></script>
<script src="javascripts/sweetalert.min.js"></script>
<script src="javascripts/sweetalert.js"></script>
<script src="javascripts/jquery-1.12.4.min.js"></script>
<script>
$.getJSON("javascripts/country.json", function(json) {
var countryElement = $("#host_country");
$.each(json,function(index, value){
var countryOption = '<option value="' + value + '">'+ value + '</option>';
if(value == 'Uganda') {
countryOption = '<option value="' + value + '" selected>'+ value + '</option>';
}
countryElement.append(countryOption);
});
});</script>
</body>
</html>
<?php
if(!isset($_SESSION))
session_start();
if(isset($_SESSION['email']))
{
header("location: welcome.php");
}
require 'dbconnect.php';
if(isset($_POST['email'])&&isset($_POST['uname'])&&isset($_POST['password'])&&isset($_POST['host_country'])&&!empty($_POST['email'])&&!empty($_POST['uname']))
{
$reCaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $reCaptchaUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=".$_settings['reCaptcha']['server_key']."&response=".$_POST['g-recaptcha-response']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
$reCaptchaResponse = json_decode($server_output);
**if(!$reCaptchaResponse->success)**
{
echo "<script type='text/javascript'>salert('Oops','Captcha not verified','error');</script>";
}
else
{
$sql="CALL dupemail('$_POST[email]')";
$result = mysqli_query($connection,$sql);
$connection -> next_result(); //used when there are multiple procedure calls, use after ecah procedure call
if(mysqli_num_rows($result)>=1) //check if it is a duplicate email
{
echo "<script type='text/javascript'>salert('Oops','User with this email already exists','error');</script>";
}
else
{
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($email.$password);
$newUser="CALL registration('$_POST[email]','$_POST[uname]','$password','$_POST[host_country]')"; //inserts into the user table
if(mysqli_query($connection,$newUser))
{//if successfully added user then add comrades of user with null phone numbers
$connection->next_result();
for($i=1;$i<=6;$i++)
{
$addcomrade = "CALL addcomrade($i,'$email')";//adds comrades into comrade table
mysqli_query($connection,$addcomrade);
$connection->next_result();
}
echo "<script>salert('Success','Registered Successfully','success');
setTimeout(function () {
window.location.href = 'login.php';},2000);
</script>";
}
else
echo "<script type='text/javascript'>salert('Oops','Error in adding user','error');</script>";
}
mysqli_close($connection);
}
}
?>
There are many errors in your code as follows:-
If statement in line 108 is surrounded with ** **.
alert in echo statement(line 110) is preceded by a "s"
You have forgot to add brackets to your if statement at the starting of the php code. Corrected code:-
<?php
if(!isset($_SESSION)){
session_start();}
if(isset($_SESSION['email']))
{
header("location: welcome.php");
}
require 'dbconnect.php';
if(isset($_POST['email'])&&isset($_POST['uname'])&&isset($_POST['password'])&&isset($_POST['host_country'])&&!empty($_POST['email'])&&!empty($_POST['uname']))
{
$reCaptchaUrl = 'https://www.google.com/recaptcha/api/siteverify';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $reCaptchaUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "secret=".$_settings['reCaptcha']['server_key']."&response=".$_POST['g-recaptcha-response']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
$reCaptchaResponse = json_decode($server_output);
**if(!$reCaptchaResponse->success)**
{
echo "<script type='text/javascript'>salert('Oops','Captcha not verified','error');</script>";
}
else
{
$sql="CALL dupemail('$_POST[email]')";
$result = mysqli_query($connection,$sql);
$connection -> next_result(); //used when there are multiple procedure calls, use after ecah procedure call
if(mysqli_num_rows($result)>=1) //check if it is a duplicate email
{
echo "<script type='text/javascript'>salert('Oops','User with this email already exists','error');</script>";
}
else
{
$email = $_POST['email'];
$password = $_POST['password'];
$password = md5($email.$password);
$newUser="CALL registration('$_POST[email]','$_POST[uname]','$password','$_POST[host_country]')"; //inserts into the user table
if(mysqli_query($connection,$newUser))
{//if successfully added user then add comrades of user with null phone numbers
$connection->next_result();
for($i=1;$i<=6;$i++)
{
$addcomrade = "CALL addcomrade($i,'$email')";//adds comrades into comrade table
mysqli_query($connection,$addcomrade);
$connection->next_result();
}
echo "<script>salert('Success','Registered Successfully','success');
setTimeout(function () {
window.location.href = 'login.php';},2000);
</script>";
}
else
echo "<script type='text/javascript'>salert('Oops','Error in adding user','error');</script>";
}
mysqli_close($connection);
}
}
?>
So im basically trying to call an API that is supposed to ping a given IP address, but everything ive been trying hasn't been working, they used to work in the past because these are just snippets i gathered from an old project that used to work just fine, now they dont work, ive checked to see if it logged any PHP errors, but there was nothing in the logs.
Here are my sample codes:
cURL:
<?php
if (Isset($_POST['submit'])){
$host = $_POST['host'];
$url = "http://someapi.com/ping/?host=".$host;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
}
?>
<input type="text" name="host" placeholder="IP" />
<input type="submit" name="submit" value="Geo Locate" />
<br>
<center>
<?php echo $data; ?>
</center>
</form>
#File_Get_Contents
<form action="" method="POST">
<?php
If(Isset($_POST['submit'])){
$host = $_POST['host'];
$api = #File_Get_Contents("http://someapi.com/ping/?host=" .$host. "");
echo $api;
}
?>
<input type="text" name="host" placeholder="IP" />
<input type="submit" name="submit" value="Geo Locate" />
<br>
<center>
<?php echo $api; ?>
</center>
</form>
could it be something wrong with my hosting service maybe?
I've just set up the new google recaptcha with checkbox, it's working fine on front end, however I don't know how to handle it on server side using PHP. I've tried to use the old code below but the form is sent even if the captcha is not valid.
require_once('recaptchalib.php');
$privatekey = "my key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
$errCapt='<p style="color:#D6012C ">The CAPTCHA Code wasnot entered correctly.</p>';}
Private key safety
While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.
For a little bit more detail: https://stackoverflow.com/a/323286/1680919
Verification via POST
function isValid()
{
try {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = ['secret' => '[YOUR SECRET KEY]',
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return json_decode($result)->success;
}
catch (Exception $e) {
return null;
}
}
Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).
Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }
this is solution
index.html
<html>
<head>
<title>Google recapcha demo - Codeforgeek</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<h1>Google reCAPTHA Demo</h1>
<form id="comment_form" action="form.php" method="post">
<input type="email" placeholder="Type your email" size="40"><br><br>
<textarea name="comment" rows="8" cols="39"></textarea><br><br>
<input type="submit" name="submit" value="Post comment"><br><br>
<div class="g-recaptcha" data-sitekey="=== Your site key ==="></div>
</form>
</body>
</html>
verify.php
<?php
$email; $comment; $captcha;
if(isset($_POST['email']))
$email=$_POST['email'];
if(isset($_POST['comment']))
$comment=$_POST['comment'];
if(isset($_POST['g-recaptcha-response']))
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha){
echo '<h2>Please check the the captcha form.</h2>';
exit;
}
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=YOUR SECRET KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false)
{
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else
{
echo '<h2>Thanks for posting comment.</h2>';
}
?>
http://codeforgeek.com/2014/12/google-recaptcha-tutorial/
I'm not a fan of any of these solutions. I use this instead:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
} else {
// failure
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
Easy and best solution is the following.
index.html
<form action="submit.php" method="POST">
<input type="text" name="name" value="" />
<input type="text" name="email" value="" />
<textarea type="text" name="message"></textarea>
<div class="g-recaptcha" data-sitekey="Insert Your Site Key"></div>
<input type="submit" name="submit" value="SUBMIT">
</form>
submit.php
<?php
if(isset($_POST['submit']) && !empty($_POST['submit'])){
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){
//your site secret key
$secret = 'InsertSiteSecretKey';
//get verify response data
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['g-recaptcha-response']);
$responseData = json_decode($verifyResponse);
if($responseData->success){
//contact form submission code goes here
$succMsg = 'Your contact request have submitted successfully.';
}else{
$errMsg = 'Robot verification failed, please try again.';
}
}else{
$errMsg = 'Please click on the reCAPTCHA box.';
}
}
?>
I have found this reference and full tutorial from here - Using new Google reCAPTCHA with PHP
I liked Levit's answer and ended up using it. But I just wanted to point out, just in case, that there is an official Google PHP library for new reCAPTCHA: https://github.com/google/recaptcha
The latest version (right now 1.1.2) supports Composer and contains an example that you can run to see if you have configured everything correctly.
Below you can see part of the example that comes with this official library (with my minor modifications for clarity):
// Make the call to verify the response and also pass the user's IP address
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
// If the response is a success, that's it!
?>
<h2>Success!</h2>
<p>That's it. Everything is working. Go integrate this into your real project.</p>
<p>Try again</p>
<?php
} else {
// If it's not successful, then one or more error codes will be returned.
?>
<h2>Something went wrong</h2>
<p>The following error was returned: <?php
foreach ($resp->getErrorCodes() as $code) {
echo '<tt>' , $code , '</tt> ';
}
?></p>
<p>Check the error code reference at <tt>https://developers.google.com/recaptcha/docs/verify#error-code-reference</tt>.
<p><strong>Note:</strong> Error code <tt>missing-input-response</tt> may mean the user just didn't complete the reCAPTCHA.</p>
<p>Try again</p>
<?php
}
Hope it helps someone.
To verify at server side using PHP. Two most important thing you need to consider.
1. $_POST['g-recaptcha-response']
2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';
$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
$response= json_decode($verifydata);
If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration
In the example above. For me, this if($response.success==false) thing does not work. Here is correct PHP code:
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "--your_key--";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {
// everything is ok!
} else {
// spam
}
it is similar with mattgen88, but I just fixed CURLOPT_HEADER, and redefine array for it work in domain.com host server. this one doesn't work on my xampp localhost. Those small error but took long to figure out. this code was tested on domain.com hosting.
$privatekey = 'your google captcha private key';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 'Content-Type: application/json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
echo 'captcha';
} else {
// failure
echo 'no captcha';
}
Here you have simple example. Just remember to provide secretKey and siteKey from google api.
<?php
$siteKey = 'Provide element from google';
$secretKey = 'Provide element from google';
if($_POST['submit']){
$username = $_POST['username'];
$responseKey = $_POST['g-recaptcha-response'];
$userIP = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
$response = file_get_contents($url);
$response = json_decode($response);
if($response->success){
echo "Verification is correct. Your name is $username";
} else {
echo "Verification failed";
}
} ?>
<html>
<meta>
<title>Google ReCaptcha</title>
</meta>
<body>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Write your name"/>
<div class="g-recaptcha" data-sitekey="<?= $siteKey ?>"></div>
<input type="submit" name="submit" value="send"/>
</form>
<script src='https://www.google.com/recaptcha/api.js'></script>
</body>
Source Tutorial Link
V2 of Google reCAPTCHA.
Step 1 - Go to Google reCAPTCHA
Login then get Site Key and Secret Key
Step 2 - Download PHP code here and upload src folder on your server.
Step 3 - Use below code in your form.php
<head>
<title>FreakyJolly.com Google reCAPTCHA EXAMPLE form</title>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
require('src/autoload.php');
$siteKey = '6LegPmIUAAAAADLwDmXXXXXXXyZAJVJXXXjN';
$secret = '6LegPmIUAAAAAO3ZTXXXXXXXXJwQ66ngJ7AlP';
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$gRecaptchaResponse = $_POST['g-recaptcha-response']; //google captcha post data
$remoteIp = $_SERVER['REMOTE_ADDR']; //to get user's ip
$recaptchaErrors = ''; // blank varible to store error
$resp = $recaptcha->verify($gRecaptchaResponse, $remoteIp); //method to verify captcha
if ($resp->isSuccess()) {
/********
Add code to create User here when form submission is successful
*****/
} else {
/****
// This variable will have error when reCAPTCHA is not entered correctly.
****/
$recaptchaErrors = $resp->getErrorCodes();
}
?>
<form autcomplete="off" class="form-createuser" name="create_user_form" action="" method="post">
<div class="panel periodic-login">
<div class="panel-body text-center">
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_user_name" required="">
<span class="bar"></span>
<label>Username</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="text" autcomplete="off" class="form-text" name="new_phone_number" required="">
<span class="bar"></span>
<label>Phone</label>
</div>
<div class="form-group form-animate-text" style="margin-top:40px !important;">
<input type="password" autcomplete="off" class="form-text" name="new_user_password" required="">
<span class="bar"></span>
<label>Password</label>
</div>
<?php
if(isset($recaptchaErrors[0])){
print('Error in Submitting Form. Please Enter reCAPTCHA AGAIN');
}
?>
<div class="g-recaptcha" data-sitekey="6LegPmIUAAAAADLwDmmVmXXXXXXXXXXXXXXjN"></div>
<input type="submit" class="btn col-md-12" value="Create User">
</div>
</div>
</form>
</body>
</html>
In response to #mattgen88's answer ,Here is a CURL method with better arrangement:
//$secret= 'your google captcha private key';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.google.com/recaptcha/api/siteverify",
CURLOPT_HEADER => "Content-Type: application/json",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => FALSE, // to disable ssl verifiction set to false else true
//CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array(
'secret' => $secret,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
)
));
$response = json_decode(curl_exec($curl));
$err = curl_error($curl);
curl_close($curl);
if ($response->success) {
echo 'captcha';
}
else if ($err){
echo $err;
}
else {
echo 'no captcha';
}
Check below example
<script src='https://www.google.com/recaptcha/api.js'></script>
<script>
function get_action(form)
{
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
else
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
</script>
<form autocomplete="off" method="post" action=submit.php">
<input type="text" name="name">
<input type="text" name="email">
<div class="g-recaptcha" id="rcaptcha" data-sitekey="site key"></div>
<span id="captcha" style="color:red" /></span> <!-- this will show captcha errors -->
<input type="submit" id="sbtBrn" value="Submit" name="sbt" class="btn btn-info contactBtn" />
</form>