I am using a PHP script to push messages onto android devices via GCM. I have an html form that takes in a text input as the message and then pushes this message to the android device.
Now when i tried it with two separate fields 1. Excerpt 2. Message
My android device receives a null message.
I need to know where am I going wrong.
This is my HTML Form
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>User:</label> <span><?php echo $row["id"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="excerpt" cols="10" class="txt_excerpt" placeholder="Type excerpt here"></textarea>
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
This is the ajax Script
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
$('.txt_excerpt').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
This is the Send_message.php code
if (isset($_GET["regId"]) && isset($_GET["message"]) && isset($_GET["excerpt"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
$excerpt = $_GET["excerpt"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("news" => $message, "exc" => $excerpt);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
This is the GCM.php Code
public function send_notification($registatoin_ids, $message, $excerpt) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
This is the android GCMIntentService Code
#Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("news");
String excerpt = intent.getExtras().getString("exc");
Log.i("Received ->", excerpt+" "+message);
if(message!=null)
{
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
}
All I see on my device is a blank notification whenever I push a message from the server.
Related
I'm making an auto SMS system. But SMS provider gave me post method form but I want it to modify with curl command by my own.
they provided me
<head>
<title>SMS</title>
</head>
<body>
<form name="sms" method="post" >
<input type="text" placeholder="send to number" name="to" /><br />
<input type="textarea" placeholder="sms" name="msg" /><br />
<input type="submit" value=" OK " />
</form>
<?php
$apikey='$2y$10$t..Yr.YDG0kXYiuLwQ78OecDgz6/qh.1xSWx77mXjczkk3AEKvTZe';
if (isset($_POST["msg"]) ) {
$sendto = $_POST["to"];
$fullNumber = '880' . substr(preg_replace('/\D/', '', $sendto), -10);
$msg = urlencode($_POST["msg"]);
// $masking='CITY PORTER';
// $masking=urlencode($masking);
// masking $url='http://example.com/smsapi/masking?api_key='.$apikey.'&smsType=text&maskingID='.$masking.'&mobileNo='.$fullNumber.'&smsContent='.$msg.'';
$url='http://example.com/smsapi/non-masking?api_key='.$apikey.'&smsType=text&mobileNo='.$fullNumber.'&smsContent='.$msg.'';
if ( !empty($_POST["to"]) && !empty($_POST["msg"])) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL =>$url,
CURLOPT_USERAGENT =>'My Browser'
));
$resp = curl_exec($curl);
echo $resp;
curl_close($curl);
}
else
{ echo "Field is empty";}
}
?>
</body>
I converted it to curl command but this is not still working. I just want to input multiple value without is set() 1 value.
$api_key = "$2y$10$mtW.yfKj18i2mTPe/0iCEuKdCfCGh9zOYYEU9AmnMrJyBb.h7fVcG";
$number = $row[mailing_no];
$message = "Dear Guardian, ". $row[name] . " has swiped his card right now";
$type= "text";
$params = array('api_key'=>$api_key, 'smsType'=>$type, 'mobileNo'=>$number, 'smsContent'=>$message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/smsapi/non-masking?".http_build_query($params, "", "&"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Accept:application/json"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close ($ch);
Try this i hope your problem will be solve
<div id="send_reply"></div>
<form name="sms" method="post" >
<input type="text" placeholder="send to number" name="to" id="phone" /><br />
<input type="textarea" placeholder="sms" name="msg" id="mess" /><br />
<input type="submit" value=" OK " id="send_btn" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#send_btn").click(function(){
var txt1=$("#phone").val();
var txt2=$("#mess").val();
$.ajax({
url : 'check.php',
method : 'GET',
data : {txt1:txt1,txt2:txt2},
success:function(dda){
$("#send_reply").html(dda);
}
});
});
});
</script>
I think we were missing double quotes for $row keys, try this:
$api_key = "$2y$10$mtW.yfKj18i2mTPe/0iCEuKdCfCGh9zOYYEU9AmnMrJyBb.h7fVcG";
$number = $row["mailing_no"];
$message = "Dear Guardian, ". $row["name"] . " has swiped his card right now";
$type= "text";
$params = array('api_key'=>$api_key, 'smsType'=>$type, 'mobileNo'=>$number, 'smsContent'=>$message);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/smsapi/non-masking?".http_build_query($params, "", "&"));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "Accept:application/json"));
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($ch);
curl_close ($ch);
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've built a html web form that collects subscriber info through AJAX and process thru a php script, and send to mailchimp.
Form submission worked fine until SSL was added to the domain. I keep on getting 405 Not Allowed when I try to submit the form. And I couldn't figure out what went wrong. I have a feeling this has to do with the Nginx server configuration, but I'm no expert in this area and don't know where to look.
After some research, I came across a few posts discussing how 'Nginx does not allow POST to static content' which I'm not sure if it applies to my case because this issue only occurred after ssl was added (I'm using Nginx + php on Alicloud). Below are my codes:
<section id="mailchimp">
<div class="container">
<form id="form" method="POST" action="action.php">
<p class="sub-lead">* indicates required.</p>
<input type="email" name="EMAIL" id="form_email" placeholder="Email Address *" required="required">
<input type="text" name="FNAME" id="form_fname" placeholder="First Name *" required="required">
<input type="text" name="LNAME" id="form_lname" placeholder="Last Name *" required="required">
<input type="text" name="PHONE" id="form_phone" placeholder="Phone Number *" required="required">
<select name="ROOM" id="room">
<option value="" disabled selected>I am interested in...</option>
<option value="1 Bedroom">1 Bedroom</option>
<option value="2 Bedroom">2 Bedroom</option>
<option value="3 Bedroom">3 Bedroom</option>
</select>
<input type="checkbox" id="opt-in" name="opt-in" value="opt-in" required="required">Yes, I want to receive current & future projects info from the development team & its affiliates.<br>
<input type="submit" value="submit" id="submit">
<div id="signup-result"></div>
</form>
</div>
</section>
php
<?php
//fill in these values for with your own information
$api_key = 'xxxxxxxx-us16';
$datacenter = 'us16';
$list_id = 'xxxxxxxxx;
$email = $_POST['email'];
$fname = $_POST['first_name'];
$lname = $_POST['last_name'];
$phone = $_POST['phone'];
$room = $_POST['room'];
$country = $_POST['country'];
$status = 'subscribed';
if(!empty($_POST['status'])){
$status = $_POST['status'];
}
$url = 'https://'.$datacenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/';
$username = 'apikey';
$password = $api_key;
$data = array("email_address" => $email,
"status" => $status,
"merge_fields" => array(
"FNAME" => $fname,
"LNAME" => $lname,
"PHONE" => $phone,
"ROOM" => $room,
)
);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$api_key");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
here's the ajax
// Mailchimp Form
$('#form').submit(function(e){
e.preventDefault();
//grab attributes and values out of the Form
var data = {
email: $('#form_email').val(),
first_name: $('#form_fname').val(),
last_name: $('#form_lname').val(),
phone: $('#form_phone').val(),
room: $('#room').val(),
};
var endpoint = $(this).attr('action');
//make the ajax request
$.ajax({
method: 'POST',
dataType: "json",
url: endpoint,
data: data
}).done(function(data){
if(data.id){
//successful adds will have an id attribute on the object
window.location='thankyou.html'
} else if (data.title == 'Member Exists') {
//MC wil send back an error object with "Member Exists" as the title
alert('It looks like you have already signed up with this email address. If you have any questions, please feel free to contact us by email or phone.');
} else {
//something went wrong with the API call
alert('Oops, we could not reach server at the moment, please try again later.');
}
}).fail(function(){
//the AJAX function returned a non-200, probably a server problem
alert('oh no, there has been a problem');
});
});
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'm new to JSON and Yelp's API. I'm trying to search the API with a form. Here's my HTML:
<div>
<form action="sample.php" method="post">
<label>Term</label> <input name="term" id="term" type="text"/>
<label>Location</label> <input name="location" id="location" type="text"/>
<input id="submit" type="submit" name="submitRest" value="SUBMIT">
</form>
<div id="success"></div>
<div id="result">Result</div>
</div>
I'm submitting the form via ajax here:
<script type="text/javascript">
$('form').submit(function(evt){
evt.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax(url, {
data : formData,
type : "POST",
success : function(response){
$('#success').html("<p>It worked!</p><p>" + <?php $getYelpData ?> + "</p>")
}
});
});
</script>
The problem lies in "sample.php". It consists of this Oauth call:
require_once('lib/OAuth.php');
$Term = (isset($_POST['term'])) ? $_POST['term'] : '';
$Location = (isset($_POST['location'])) ? $_POST['location'] : '';
function getYelpData($Term, $Location) {
$URL = "http://api.yelp.com/v2/search?term=" . $Term . "&location=" . $Location;
$CONSUMER_KEY = -;
$CONSUMER_SECRET = -;
$TOKEN = -;
$TOKEN_SECRET = -;
$AuthToken = new OAuthToken($TOKEN, $TOKEN_SECRET);
$Consumer = new OAuthConsumer($CONSUMER_KEY, $CONSUMER_SECRET);
$AuthRequest = OAuthRequest::from_consumer_and_token(
$Consumer,
$AuthToken,
'GET',
$URL
);
$AuthRequest->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $Consumer, $AuthToken);
$Handle = curl_init($AuthRequest->to_url());
curl_setopt($Handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($Handle, CURLOPT_HEADER, 0);
$YelpResponse = curl_exec($Handle); // Yelp response
curl_close($Handle);
return json_decode($YelpResponse,true);
}
How do I grab the JSON data from $YelpResponse? The ajax displays the success message, so I know it's working, but I'm not sure how to get the data I want out of it.