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>
Related
I am trying to POST HTML form login credentials(email & password) to an endpoint using PHP cURL and subsequently redirect to a different page(admin/index.php) after a successful login. However, I keep getting {"success":"false","message":"please provide email and password"} error from my nodejs login endpoint. I am inexperienced with cURL hence I am failing to notice where I am getting it wrong. Please help.
<?php
session_start();
// include('includes/config.php');
$error = ''; //Variable to Store error message;
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['password'])) {
$error = "Email or Password is Invalid";
} else {
//Define $user and $pass
$email = ($_POST['email']);
$password = ($_POST['password']);
$url = 'http://localhost:5000/auth/login';
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERPWD, $email.":".$password);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
$result = curl_exec($curl);
echo $result;
if ($result == 200) {
$_SESSION['alogin'] = $email;
header("Location: admin/index.php"); // Redirecting to other page
} else {
$error = "Try to login.";
}
curl_close($curl);
}
}
?>
Here is the HTML form.
<div class="panel panel-info">
<div class="panel-heading">
LOGIN FORM
</div>
<div class="panel-body">
<form role="form" method="post" name="login" action="index.php" role="form">
<div class="form-group">
<label>Enter Email</label>
<input class="form-control" type="email" name="email" autocomplete="off" />
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control" type="password" name="password" autocomplete="off" />
</div>
<button type="submit" name="login" class="btn btn-info">LOGIN</button>
</form>
</div>
</div>
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode(['email' => $email, 'password' =>$password]));
There are two formats for CURLOPT_POSTFIELDS Neither is JSON.
$post = 'key1=value1&key2=value2&key3=value3';
$post = array('key1'=>$value1,'key2'=>$value2,'key3'=>'value3');
You may need to use urlencode() on username and password.
Were you told to use the CURLOPT_USERPWD,
That is unconventional.
And this is just wrong. It might work, but it is still wrong.
if ($result == 200) {
Use
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if ($status == 200){...
The Mailchimp API returns error 400 if I try to subscribe a user that is already subscribed. Then I found that if I unsubscribe and attempt to resubscribe again I also get error 400. Is there a way to differentiate between these cases?
Mailchimp's error documentation says that 400 is returned for different reasons (bad request, invalid resource, invalid action, JSON parse exception). There doesn't seem to be a way to get more specific messages, and certainly no way to determine whether the issue is that user is already subscribed vs. recently unsubscribed.
Any idea how to return more useful error messages?
Here is my test code (based on this reference):
<?php
$statusMsg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['subscribe'])) {
if (!empty($_POST['email']) && !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
// input sanitation
array_walk_recursive($_POST, function(&$value) {
$value = htmlspecialchars(stripslashes(trim($value)));
});
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$email = $_POST['email'];
// MailChimp API credentials
$apiKey = '<my test API key>';
$listId = '<my list id>';
// MailChimp API URL
$dataCenter = substr($apiKey,strpos($apiKey,'-') + 1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/';
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'FNAME' => $fname,
'LNAME' => $lname
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// store the status message based on response code
if ($httpCode == 200) {
$statusMsg = '<p style="color: #34A853">You have successfully subscribed.</p>';
} else {
switch ($httpCode) {
case 400: // problem: this also happens when user is unsubscribed
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again. Error code ' . $httpCode . '.';
break;
}
$statusMsg = '<p style="color: red;">'.$msg.'</p>';
}
} else {
$statusMsg = '<p style="color: red;">Please enter valid email address.</p>';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mailchimp API Test</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<div id="container">
<h1>Subscribe to our Newsletter</h1>
<?php echo $statusMsg; ?>
<form method="post">
<input type="text" name="subscribe" value="subscribe" aria-hidden="true" readonly hidden>
<p><label for="fname"> First Name:</label><br>
<input id="fname" type="text" name="fname" /></p>
<p><label for="lname"> Last Name:</label><br>
<input id="lname" type="text" name="lname" /></p>
<p><label for="email"> Email address:</label><br>
<input id="email" type="text" name="email" /></p>
<input type="submit" value="Submit" />
</form>
</div>
</main>
</body>
</html>
I have a login form that uses NATS API (Next-Generation Administration and Tracking System). In my form I have username and password fields that successfully log user on site. Now I want user to be able to also write his email if he wishes in username field and to be successfully logged in on site. I need to perform an additional search on that members email to get their username from NATS to authenticate them. Since I am using the member_auth table if a member enters an email address I would need to get the username from NATS using the API to perform the login. I need help on how to write that in this function that logs in user.
function.php
function elx_nats_api($endpoint = "member/details", $member_username, $member_email, $nats_site_id = 1){
$API_credentials["URL"] = "http://nats.site.com/api/";
$API_credentials["USR"] = "Oktogon";
$API_credentials["KEY"] = "51e2a35b50d9fd1f15a31827f32427edd";
if( $member_username == "" ) $member_username = $_SERVER["REMOTE_USER"];
// CURL
$curl = curl_init();
$data = array(
'username' => $member_username,
'email' => $member_email,
'full_info' => true,
'subscriptions' => true,
'siteid' => $nats_site_id
);
$data_string = http_build_query($data);
$url = $API_credentials["URL"] . $endpoint . "?" . $data_string;
$headers = array(
"api-key: ".$API_credentials["KEY"],
"api-username: ".$API_credentials["USR"]
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, $url);
$resp = curl_exec($curl);
$result = json_decode($resp, true);
// Close request to clear up some resources
curl_close($curl);
// Return the Result Array
return $result;
}
form.php
%%PRX_FORM%%
<div class="logbox">
<div class="box clear">
<h2>Members Area</h2>
<div class="logTypes">
<input type=text name=uid class="logtextbox" placeholder="Username">
<input type=password name=pwd class="logtextbox" placeholder="Password"><br>
<input type=text name=img class="logtextbox" placeholder="Enter the code shown below"></br>
<img style="margin: 0 auto;" src="/img.cptcha">
<div style="text-align: center">Remember my login: <input name=rmb type=checkbox value=”y”></div>
</div>
</div>
<input type="submit" value="submit" class="logBtn">
</div>
</form>
I am using NATS 4.1 and any help is appreciated.
I am trying to add a php file that adds a new subscriber to my MailChimp list. Here is my form that SHOULD trigger the php file to add the new subscriber:
<form action="/scripts/freemonth_action.php" class="email_form_freemonth" method="post">
<h3>Get your first month free</h3>
<div class="form-group customised-formgroup"> <span class="icon-user"></span>
<input type="text" name="full_name" class="form-control" placeholder="Name">
</div>
<div class="form-group customised-formgroup"> <span class="icon-envelope"></span>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-telephone"></span>
<input type="text" name="phone" class="form-control" placeholder="Phone (optional)">
</div>-->
<div class="form-group customised-formgroup"> <span class="icon-laptop"></span>
<input type="text" name="website" class="form-control" placeholder="Website (optional)">
</div>
<!--<div class="form-group customised-formgroup"> <span class="icon-bubble"></span>
<textarea name="message" class="form-control" placeholder="Message"></textarea>
</div>-->
<div>
<br>
<button style="margin: 0 auto" type="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
</div>
</form>
And here is freemonth_action.php:
<?php
session_start();
if(isset($_POST['submit'])){
$name = trim($_POST['full_name']);
$email = trim($_POST['email']);
if(!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false){
// MailChimp API credentials
$apiKey = '6b610769fd3353643c7427db98d43ad6-us16';
$listID = '0cf013d1d9';
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
'merge_fields' => [
'NAME' => $name,
]
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo json_encode($result);
// store the status message based on response code
if ($httpCode == 200) {
$_SESSION['msg'] = '<p style="color: #34A853">You have successfully subscribed to CodexWorld.</p>';
} else {
switch ($httpCode) {
case 214:
$msg = 'You are already subscribed.';
break;
default:
$msg = 'Some problem occurred, please try again.';
break;
}
$_SESSION['msg'] = '<p style="color: #EA4335">'.$msg.'</p>';
}
}else{
$_SESSION['msg'] = '<p style="color: #EA4335">Please enter valid email address.</p>';
}
}
I'm not even sure how to debug this, because when i do echo $result (or anything like that) I do not see anything on the page or logged to the console. I'm also open to any suggestions that use javascript as long as it is still the 3.0 API.
Your subscription code works fine. The reason you aren't seeing any result is because isset($_POST['submit']) looks for an element with the name 'submit' rather than the type 'submit'. Just add the name attribute to your button, and it should work for you:
<button style="margin: 0 auto" type="submit" name="submit" class="btn btn-fill full-width">GET FREE MONTH<span class="icon-chevron-right"></span></button>
Also, you should keep the API key secret so other people can't access your MailChimp account through the API. I'd recommend disabling your current key and creating a new one. See MailChimp's knowledgebase article about API Keys for more details.
my site looks like this.
<?php
include 'dbd.php'; //DB Login details
?>
<!DOCTYPE html>
<html>
<head>
<script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<?php
$showFormular = true;
if (isset($_POST['submit'])) {
$error = false;
if (!$error) {
$statement = $pdo->prepare("INSERT INTO table (email, name) VALUES (:email, :name,)");
$result = $statement->execute(array(
'email' => $email,
'name' => $name
));
if ($result) {
echo "Your Registration was Successful";
$showFormular = false;
} else {
echo 'Could not register your Account';
}
}
}
if ($showFormular) {
?>
<form action="<?php echo ($_SERVER['PHP_SELF']); ?>" method="post">
<input placeholder="Your Forum Name Here" name="name" required>
<input placeholder="Your Forum Email Here" name="email" required>
<div class="g-recaptcha" data-sitekey="public key"></div>
<input name="submit" type="submit">
</form>
<?php
}
?>
</body>
</html>
The Problem what I have is that I dont know how to implement the Serverside ReCaptcha Check. I tried it with the following method but there I get obviously the error that the function is empty because its getting executed directly.
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.google.com/recaptcha/api/siteverify',
CURLOPT_POST =>1,
CURLOPT_POSTFIELDS => [
'secret' => 'privat key',
'response' => $_POST['g-recaptcha-response'],
],
]);
I hope I explained it good enough that someone can help me.
Why are you trying to use curl command ? You can do this by directly with php code.
First of all download this php reCaptcha library and import your project : reCaptcha gitHub
Secondly, after you action call your php and implement this on your php code.
require_once('your-imported-autoload.php-path'); ex:Assets/reCaptcha/autoload.php
$privatekey = "-your private key-";
$recaptcha = new \ReCaptcha\ReCaptcha($privatekey);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'],
$_SERVER['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
// Your code here to handle a successful verification
}
For last, for cURL you are trying to connect through SSL and have to handle it
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);