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){...
Related
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.
When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:
array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers
I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.
Any Ideas? Thanks for taking the time to help me out.
PHP:
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '',
'response' => $user_response
);
foreach($fields as $key=>$value)
$fields_string .= $key . '=' . $value . '&';
$fields_string = rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);
if (!$res['success']) {
// What happens when the CAPTCHA wasn't checked
echo '<p>Please Check the Security CAPTCHA Box.</p><br>';
} else {
// If CAPTCHA is successfully completed...
// Paste mail function or whatever else you want to happen here!
$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";
try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");
$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];
$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
// Echo Successful attempt
echo "<p Data added to database.</p></br></br>";
}
catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
HTML:
<article class="contact-form">
<form action="" method="POST">
<div class="col-md-5 col-md-offset-1 contact-form-left">
<input class="Fname" type="text" placeholder="FIRST NAME*">
<input class="Lname" type="text" placeholder="LAST NAME*">
<input class="Email" type="email" placeholder="EMAIL*">
</div>
<div class="col-md-5 contact-form-right text-right">
<div class="g-recaptcha" data-sitekey=""></div>
<br>
<input type="submit" class="submit-btn" value="Subscribe">
</div>
</form>
</article>
In your html form, the name and email fields don't have a name attribute so they aren't included in the response.
Thanks KAF, I just realize that and fix it. I was so fixed on my php, I didn't notice it until I posted it here. It always the simple things.
Fixed HTML:
<article class="contact-form">
<form action="" method="POST">
<div class="col-md-5 col-md-offset-1 contact-form-left">
<input name="Fname" type="text" placeholder="FIRST NAME*">
<input name="Lname" type="text" placeholder="LAST NAME*">
<input name="Email" type="email" placeholder="EMAIL*">
</div>
<div class="col-md-5 contact-form-right text-right">
<div class="g-recaptcha" data-sitekey=""></div>
<br>
<input type="submit" class="submit-btn" value="Subscribe">
</div>
</form>
</article>
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>
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