How do I implement a MailChimp API form embed? - php

sorry for the perhaps naive question, but I have absolutely 0 experience in web design and I've been plowing through .html/.css for 2 days straight, and I think it's time I just seek some help.
I'm making a simple landing page for a conference, and I've been using a few templates. The most recent template I'm using is perfect, except the email signup sends direct emails to my account, rather than creating a list using a service such as mailchimp - highly inefficient.
A previous template I tried out, however, did implement mailchimp, and I was wondering how I might just grab its code and throw it in the current template I have.
Here is the subscribe.php from the mailchimp template:
<?php
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $_POST['email'];
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>
and here is the snippet of code in index.html:
<div class="row">
<div class="col-md-6 col-sm-12 col-md-offset-3 subscribe">
<form class="form-horizontal" role="form" action="subscribe.php" id="subscribeForm" method="POST">
<div class="form-group">
<div class="col-md-7 col-sm-6 col-sm-offset-1 col-md-offset-0">
<input class="form-control input-lg" name="email" type="email" id="address" placeholder="Enter your email" data-validate="validate(required, email)" required="required">
</div>
<div class="col-md-5 col-sm-4">
<button type="submit" class="btn btn-success btn-lg">SIGN UP TO BE NOTIFIED</button>
</div>
</div>
</form>
<span id="result" class="alertMsg"></span> </div>
</div>
For reference, here are the subscribe.php and index.html snippets from the non-mailchimp template:
Subscribe.php
<?php
if ( isset( $_POST['newsletter_submit'] ) ) {
// Initialize error array
$newsletter_errors = array();
// Check email input field
if ( trim( $_POST['newsletter_email'] ) === '' )
$newsletter_errors[] = 'Email address is required';
elseif ( !preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) ) )
$newsletter_errors[] = 'Email address is not valid';
else
$newsletter_email = trim( $_POST['newsletter_email'] );
// Send email if no input errors
if ( empty( $newsletter_errors ) ) {
$email_to = "register#neustep.org"; // Change to your own email address
$subject = "NeuSTEP Subscription";
$body = "Subscriber details: " . $newsletter_email . "\r\n";
mail( $email_to, $subject, $body, $headers );
echo 'Thank you for subscribing!';
} else {
echo 'Please go back and correct the following errors:<br />';
foreach ( $newsletter_errors as $error ) {
echo $error . '<br />';
}}}
?>
Index.html snippet
<div class="newsletter">
<form action="subscribe.php" method="post" id="newsletter-form">
<p class="form-field">
<label for="newsletter_email" class="visually-hidden">Your email address</label>
<i class="icon ion-paper-airplane" aria-hidden="true"></i>
<input type="text" name="newsletter_email" id="newsletter_email" value="" placeholder="Your email address" />
</p>
<p class="form-submit">
<input type="submit" name="newsletter_submit" id="newsletter_submit" value="Get Notified" />
</p>
</form>
</div>
thanks for helping! sorry for the long post. I'm not sure what the etiquette on stackoverflow is, so if i'm asking a crappy question, let me know.

Your form is ok, and you need to implement a handler for subscribing like;
subscribe.php
<?php
if (empty($_POST["newsletter_email"]) {
die("You should provide email!");
} else if (!preg_match( "/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z] {2,4}$/i", trim( $_POST['newsletter_email'] ) )) {
die("Email address is not valid!");
} else {
$newsletter_email = trim( $_POST['newsletter_email'] );
}
$apiKey = '';
$listId = '';
$double_optin=true;
$send_welcome=true;
$email_type = 'html';
$email = $newsletter_email;
//replace us2 with your actual datacenter
$submit_url = "http://us1.api.mailchimp.com/1.3/?method=listSubscribe";
$data = array(
'email_address'=>$email,
'apikey'=>$apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error){
echo $data->error;
} else {
echo "Thanks! We'll keep you updated on the conference :)";
}
?>

Related

How to pass user input to an api endpoint using php curl?

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){...

MailChimp Add Subscriber using API 3.0 PHP

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.

Linking Mailchimp to Sign-Up Boxes

I am linking an e-mail sign-up and a post code (UK English for zip code) input box (see html code below) to an existing Mailchimp e-mail list. I have taken out the $apiKey, $listId and $submit_url identifiers from the code below. I have been able to successfully link the Mailchimp list to the e-mail input (so that e-mail address are populated when they are input in the Mailchimp list but I cannot figure out how to get post codes to automatically update in mailchimp list when they are input).
I am relatively new to php and would be so grateful for any help.
<div class="subscribe">
<form method="post" action="bokacsubscribe.php" role="form">
<input type="email" placeholder="Enter your e-mail address..." class="subscribe-input" name="email" style="margin-bottom: 10px;">
<form method="post" action="bokacsubscribe.php" role="form">
<input type="email" placeholder="Enter your postcode" class="subscribe-input" name="postcode" style="margin-bottom: 10px;">
<button type="submit" class="btn btn-subscribe success" style="border-radius:120px;background-color:rgb(241,174,200);border:1px solid rgb(241,174,200)"><b>Send</b></button>
<input type="hidden" name="referr" id="referr"/>
</form>
</div>
</div>
<?php
// Credits: https://gist.github.com/mfkp/1488819
session_cache_limiter('nocache');
$apiKey = ''; - // How get your Mailchimp API KEY - http://kb.mailchimp.com/article/where-can-i-find-my-api-key
$listId = ''; - // How to get your Mailchimp LIST ID - http://kb.mailchimp.com/article/how-can-i-find-my-list-id
$submit_url = ""; - // Replace us2 with your actual datacenter
$double_optin = false;
$send_welcome = false;
$email_type = 'html';
$email = $_POST['email'];
$merge_vars = array( 'YNAME' => $_POST['yname'] );
$data = array(
'email_address' => $email,
'apikey' => $apiKey,
'id' => $listId,
'double_optin' => $double_optin,
'send_welcome' => $send_welcome,
'merge_vars' => $merge_vars,
'email_type' => $email_type
);
$payload = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $submit_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($payload));
$result = curl_exec($ch);
curl_close ($ch);
$data = json_decode($result);
if ($data->error) {
// do whatever you do on failure here
} else {
// do whatever you do on success here
$arrResult = array ('response'=>'success');
}

How to validate Google reCAPTCHA v3 on server side?

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>

Problems sending data to PHP with Curl

I need some advice with this curl script. I am trying to send values from the FORM to the curl script, but seems that the curl script doesn`t receive the info.
Here is the script:
<?php
if($_SERVER['REQUEST_METHOD'] != 'POST') {
$self = $_SERVER['PHP_SELF'];
?>
<form method="post" action="<?php echo $self; ?>" class="form-horizontal">
<fieldset>
<legend>SMS Contact</legend>
<div class="control-group">
<label for="basic" class="control-label">Name and Surname</label>
<div class="controls">
<input type="text" name="name" id="name" disabled class='input-square' value="<?php print $contactname;?> <?php print $contactsurname;?>">
</div>
</div>
<div class="control-group">
<label for="basic" class="control-label">Mobile No</label>
<div class="controls">
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
</div>
</div>
<div class="control-group">
<label for="textcounter" class="control-label" id="textcounter">Textarea</label>
<div class="controls">
<textarea name="textcounter" id="textcounter" class='input-square span9 counter' data-max="160" rows='6'></textarea>
</div>
</div>
<div class="form-actions">
<button class="btn btn-primary" type="submit">Send SMS</button>
</div>
</fieldset>
</form>
<?php
} else {
$mobile = $_POST['mobile'];
$text = $_POST['textcounter'];
$username = 'xxxx';
$password = 'xxxx';
// Set Timezone
date_default_timezone_set('Africa/Johannesburg');
$date = date("m/d/y G.i:s", time());
// Create Unique ID
$code = md5(time());
$newid = $code.$clientid;
$sql="INSERT INTO sent_itmes (sent_id, sent_message, sent_date, sent_quantity, client_id, sent_mobile)VALUES('$newid', '$text', '$date', '1', '$clientid', '$mobile')";
$result=mysql_query($sql);
$url = "http://bulksms.2way.co.za/eapi/submission/send_sms/2/2.0"; // URL to calc.cgi
$fields = array(
'site'=>'',
'username'=>($username),
'password'=>($password),
'message'=>urlencode($text),
'msisdn'=>urlencode($mobile)
);
$fields_string="?";
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
ob_start();
curl_exec($ch);
ob_end_clean();
echo '<div class="alert alert-block alert-success">
<a class="close" data-dismiss="alert" href="#">×</a>
<h4 class="alert-heading">Success!</h4>
Your message has been Sent!
</div><br/><br/>Search Contact';
//close connection
curl_close($ch);
}
?>
When submitting the form, I get the error from response server "No recipients specified", so this means that the form value "mobile" doesnt pass though the value to the curl.
Help please, going off my mind.
Try adding a header that describes the content you post and maybe content you apply
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded',
'Accept: text/html',
'Expect: ',
) );
use this for sending data
//open connection
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,POSTVARS.$fields_string); // this line is edited..
curl_setopt($ch, CURLOPT_FOLLOWLOCATION ,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
//execute post
ob_start();
curl_exec($ch);
your order was wrong...
more info http://www.askapache.com/php/sending-post-form-data-php-curl.html
When you submit form with disabled field, that field do not sent:
<input type="text" name="mobile" id="mobile" disabled class='input-square' value="<?php echo urlencode($contactmobile);?>">
If you want to send "mobile", you should add hidden field for it. And maybe replace disabled field name

Categories