I am currently following the tutorial from this website:
http://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/
I am able to send notification from the firebase console but failed to do so from PHP.
config_firebase.php
<?php
// Firebase API Key
define('FIREBASE_API_KEY', 'xxx');
?>
push_firebase.php
<?php
class Push {
// push message title
private $title;
private $message;
private $image;
// push message payload
private $data;
// flag indicating whether to show the push
// notification or not
// this flag will be useful when perform some opertation
// in background when push is recevied
private $is_background;
function __construct() {
}
public function setTitle($title) {
$this->title = $title;
}
public function setMessage($message) {
$this->message = $message;
}
public function setImage($imageUrl) {
$this->image = $imageUrl;
}
public function setPayload($data) {
$this->data = $data;
}
public function setIsBackground($is_background) {
$this->is_background = $is_background;
}
public function getPush() {
$res = array();
$res['data']['title'] = $this->title;
$res['data']['is_background'] = $this->is_background;
$res['data']['message'] = $this->message;
$res['data']['image'] = $this->image;
$res['data']['payload'] = $this->data;
$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
?>
firebase.php
<?php
class Firebase {
// sending push message to single user by firebase reg id
public function send($to, $message) {
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Sending message to a topic by topic name
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// sending push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'to' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// function makes curl request to firebase servers
private function sendPushNotification($fields) {
require_once __DIR__ . '/config_firebase.php';
// Set POST variables
$url = 'https://fcm.googleapis.com/fcm/send';
$headers = array(
'Authorization: key=' . FIREBASE_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);
return $result;
}
}
?>
push_notification_firebase.php
<html>
<head>
<title>AndroidHive | Firebase Cloud Messaging</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="//www.gstatic.com/mobilesdk/160503_mobilesdk/logo/favicon.ico">
<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
<style type="text/css">
body{
}
div.container{
width: 1000px;
margin: 0 auto;
position: relative;
}
legend{
font-size: 30px;
color: #555;
}
.btn_send{
background: #00bcd4;
}
label{
margin:10px 0px !important;
}
textarea{
resize: none !important;
}
.fl_window{
width: 400px;
position: absolute;
right: 0;
top:100px;
}
pre, code {
padding:10px 0px;
box-sizing:border-box;
-moz-box-sizing:border-box;
webkit-box-sizing:border-box;
display:block;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
word-wrap: break-word;
width:100%; overflow-x:auto;
}
</style>
</head>
<body>
<?php
// Enabling error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
require_once __DIR__ . '/firebase.php';
require_once __DIR__ . '/push_firebase.php';
$firebase = new Firebase();
$push = new Push();
// optional payload
$payload = array();
$payload['team'] = 'India';
$payload['score'] = '5.6';
// notification title
$title = isset($_GET['title']) ? $_GET['title'] : '';
// notification message
$message = isset($_GET['message']) ? $_GET['message'] : '';
// push type - single user / topic
$push_type = isset($_GET['push_type']) ? $_GET['push_type'] : '';
// whether to include to image or not
$include_image = isset($_GET['include_image']) ? TRUE : FALSE;
$push->setTitle($title);
$push->setMessage($message);
if ($include_image) {
$push->setImage('http://api.androidhive.info/images/minion.jpg');
} else {
$push->setImage('');
}
$push->setIsBackground(FALSE);
$push->setPayload($payload);
$json = '';
$response = '';
if ($push_type == 'topic') {
$json = $push->getPush();
$response = $firebase->sendToTopic('global', $json);
} else if ($push_type == 'individual') {
$json = $push->getPush();
$regId = isset($_GET['regId']) ? $_GET['regId'] : '';
$response = $firebase->send($regId, $json);
}
?>
<div class="container">
<div class="fl_window">
<div><img src="http://api.androidhive.info/images/firebase_logo.png" width="200" alt="Firebase"/></div>
<br/>
<?php if ($json != '') { ?>
<label><b>Request:</b></label>
<div class="json_preview">
<pre><?php echo json_encode($json) ?></pre>
</div>
<?php } ?>
<br/>
<?php if ($response != '') { ?>
<label><b>Response:</b></label>
<div class="json_preview">
<pre><?php echo json_encode($response) ?></pre>
</div>
<?php } ?>
</div>
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<legend>Send to Single Device</legend>
<label for="redId">Firebase Reg Id</label>
<input type="text" id="redId" name="regId" class="pure-input-1-2" placeholder="Enter firebase registration id">
<label for="title">Title</label>
<input type="text" id="title" name="title" class="pure-input-1-2" placeholder="Enter title">
<label for="message">Message</label>
<textarea class="pure-input-1-2" rows="5" name="message" id="message" placeholder="Notification message!"></textarea>
<label for="include_image" class="pure-checkbox">
<input name="include_image" id="include_image" type="checkbox"> Include image
</label>
<input type="hidden" name="push_type" value="individual"/>
<button type="submit" class="pure-button pure-button-primary btn_send">Send</button>
</fieldset>
</form>
<br/><br/><br/><br/>
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<legend>Send to Topic `global`</legend>
<label for="title1">Title</label>
<input type="text" id="title1" name="title" class="pure-input-1-2" placeholder="Enter title">
<label for="message1">Message</label>
<textarea class="pure-input-1-2" name="message" id="message1" rows="5" placeholder="Notification message!"></textarea>
<label for="include_image1" class="pure-checkbox">
<input id="include_image1" name="include_image" type="checkbox"> Include image
</label>
<input type="hidden" name="push_type" value="topic"/>
<button type="submit" class="pure-button pure-button-primary btn_send">Send to Topic</button>
</fieldset>
</form>
</div>
</body>
</html>
This is the result that I have gotten:
Request:
{"data":{"title":"This is a second test from php","is_background":false,"message":"Second test from php","image":"","payload":{"team":"India","score":"5.6"},"timestamp":"2017-02-28 3:05:55"}}
Response:
"{\"message_id\":5384787464945132888}"
I couldn't find which part went wrong. Does anyone knows what went wrong?
Edited:
push_firebase.php
public function getPush() {
$res = array();
$res['notification']['title'] = $this->title;
//$res['data']['is_background'] = $this->is_background;
//$res['data']['message'] = $this->message;
//$res['data']['image'] = $this->image;
//$res['data']['payload'] = $this->data;
//$res['data']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
firebase.php
// sending push message to single user by firebase reg id
public function send($to, $message) {
$fields = array(
'to' => $to,
'notification' => $message,
);
return $this->sendPushNotification($fields);
}
// Sending message to a topic by topic name
public function sendToTopic($to, $message) {
$fields = array(
'to' => '/topics/' . $to,
'notification' => $message,
);
return $this->sendPushNotification($fields);
}
// sending push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'to' => $registration_ids,
'notification' => $message,
);
return $this->sendPushNotification($fields);
}
Request:
{"notification":{"title":"test"}}
Response:
"{\"message_id\":5724949249510866740}"
Android code onMessageReceived:
public void onMessageReceived(RemoteMessage remoteMessage){
Log.e(TAG,"FROM: " + remoteMessage.getFrom());
if(remoteMessage == null){
return;
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
handleNotification(remoteMessage.getNotification().getBody());
}
//check if message contains a data payload
if(remoteMessage.getData().size() > 0){
Log.e(TAG,"Data Payload: " + remoteMessage.getData().toString());
try{
JSONObject json = new JSONObject(remoteMessage.getData().toString());
handleDataMessage(json);
}catch(Exception e){
Log.e(TAG,"Exception: " + e.getMessage());
}
}
}
The response shows a message_id which means the request is successful.
Did you mean to point out that you weren't able to receive the notification? If so, then this is probably because you were using a data message payload while your Android code is only handling notification message payloads. See Message Types for the description of both.
Push notifications coming from the Firebase Console are classified as notification message payloads. When you add in custom key-value pairs in the Advanced Options, it'll become a combination of both (notification and data in a single payload).
To handle data-only payloads, you'll have to use RemoteMessage.getData(). See Handling Messages in Android for more details.
Related
I have a 1 page website that is using scrollify.js.
I have 2 buttons to scroll the window to the relevant section for filling out the form and returning to the top of the page.
The first button is (icon2) with an (a) tag with a class of scrollToB.
The 2nd button (home-btn) with another (a) tag and a class of scrollTo that fades in and out so you can return to the top section on clicking this button.
Both functions to scroll and fade in and out are working until i click submit on the form and although the fade function still works on the button the seperate click functions on the 2 buttons (scrollify.move) have stopped working? This behaviour is the same whether the form fails validation or is sent?
a working example is www.devonfoodmovement.com
I have searched for hours and cant find anything relevant?
All scripts/styles are being loaded from my functions.php file
Index (front-page.php)
<?php get_header(); ?>
<article id="section_1">
<section class='section-class' data-section-name="devonfoodmovement">
<?php include('home-layout.php');?>
</section>
</article>
<article id="section_2">
<section class='section-class' data-section-name="contact us">
<?php include('form.php');?>
</section>
<div class="home-btn"><i class="fas fa-home"></i></div>
</article>
<?php get_footer(); ?>
</body>
</html>
home-layout.php
<?php ?>
<div class="container">
<div class="logo">
<div class="logo-image">
</div>
</div>
<div class="text">
<h1>Devon Food Movement</h1>
<h2>Website under construction <br class="textbreak">follow us below on ...</h2>
</div>
<div class="icons">
<div class="icon1"></div>
<div class="icon2"></div>
<div class="icon3"></div>
<div class="icon3m"></div>
</div>
</div>
functions.php
<?php
function register_my_menus() {
register_nav_menus(
array( 'header_menu' => __( 'Header Menu', 'DevonFoodMovement'),
'footer_menu' => __( 'Footer Menu', 'DevonFoodMovement')
)
);
}
add_action('init', 'register_my_menus');
/* GOOGLE FONTS */
function DFM_styles()
{
wp_register_style('DFM', get_template_directory_uri() . '/style.css', array(), '1.0', 'all');
wp_enqueue_style('DFM');
}
add_action('wp_enqueue_scripts', 'DFM_styles');
function DFM_form()
{
wp_register_style('DFMform-css', get_template_directory_uri() . '/form.css', array(), '1.0', 'all');
wp_enqueue_style('DFMform-css');
}
add_action('wp_enqueue_scripts', 'DFM_form');
function DFM_scripts()
{
wp_register_script('j-query-min', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js' );
wp_enqueue_script('j-query-min');
wp_register_script('j-query-mob-min', 'http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js' );
wp_enqueue_script('j-query-mob-min');
wp_register_script( 'modernizr', get_template_directory_uri() . '/modernizr-1.6.min.js' );
wp_enqueue_script( 'modernizr' );
wp_register_script('scrollify-min', 'https://cdn.jsdelivr.net/npm/jquery-scrollify#1.0.17/jquery.scrollify.min.js' );
wp_enqueue_script('scrollify-min');
wp_register_script('jquery-custom', get_template_directory_uri() . '/customjs.js' );
wp_enqueue_script('jquery-custom');
}
add_action('wp_enqueue_scripts', 'DFM_scripts');
function load_fonts()
{
wp_register_style('et-googleFonts', 'https://fonts.googleapis.com/css?family=Josefin+Sans:300,400');
wp_enqueue_style( 'et-googleFonts');
}
add_action('wp_print_styles', 'load_fonts');
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
custom.js file
$(document).ready(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
$(window).resize(function(){
$('article').css({'height':($(window).height())+'px'}).css({'width':($(window).width())+'px'});
});
});
$(document).scroll(function(){
$(function() {
$.scrollify({
section: ".section-class",
sectionName : "section-name",
/*interstitialSection : ".footer-end",*/
scrollSpeed: 1000,
setHeights: true
});
});
});
$(document).scroll(function (){
if(window.location.href === "http://devonfoodmovement.com/#devonfoodmovement"){
$('.home-btn').fadeOut(500);
} else if(window.location.href === "http://devonfoodmovement.com/#contact-us") {
$('.home-btn').fadeIn(500).css('display','block');
}
});
$(document).ready(function (){
$(".scrollTo").click(function() {
$.scrollify.move(0);
});
});
$(document).ready(function (){
$(".scrollToB").click(function() {
$.scrollify.move(1);
});
});
form.php
<?php include ('form_process.php');?>
<div class="grey">
<div class="container-contact">
<form id="contact" method="post" >
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset id="field-no-ui">
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" >
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset id="field-no-ui">
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset id="field-no-ui">
<textarea id="field-no-ui" placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="sitekey" ></div>
<span class="captcha-failed"><?= $captchafailed; ?></span>
<span class="sent"><?= $sent; ?></span>
<fieldset id="field-no-ui">
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</div>
</div>
form-process.php
<?php
function post_captcha($user_response) {
$fields_string = '';
$fields = array(
'secret' => '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);
}
$res = post_captcha($_POST['g-recaptcha-response']);
$name_error = $email_error = $captchafailed = "";
$name = $email = $message = $sent = "";
if (isset($_POST['submit']) AND (!$res['success'])) {
$captchafailed = "please check reCaptcha";
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = '#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
I'm seeing a lot of issue here with the way this is put together.
First thing you can start with is to prevent the default behaviour of your move links.
$(".scrollTo").click(function(event) {
event.preventDefault();
$.scrollify.move(0);
});
I used Mobirise to create a bootstrap based website with a contact form towards the end of it. The form originally had an action just taking it to the Mobirise website. I have previously used ajax and PHP to create mailer forms, and so modified files I had on hand to handle this form. However, whenever I click on the submit button, I get the following error in the console:
POST http://www.mywebsite.com/captcha-lib.php 404 (Not Found)
I have checked and verified that php is enabled on the server (Bluehost), and that the file in question is along the correct path, and that it is on the remote server (it is). Can anyone help me determine why I am getting this error? I have provided the HTML, Ajax, and PHP for all relevant elements below, with private keys and data removed.
Below is the html for the form itself:
<form data-form-title="Let's Work Together">
<input type="hidden" value="3S/6rrqxqgfL9WCp8yG49uE1861hrI6n4k9XNv8Q5Awspyeq+y1eU1g/jgUsPbIH+KZRWaBHkHuhzqxyJ39m7DSH7QZBYD6IZFqS6415lGnscjkO2Frp6/UUrh4xDIED" data-form-email="true">
<div class="col-xs-12 col-md-8 col-md-offset-2 form-wrap">
<div class="col-xs-12">
<div class="form-group">
<label class="form-control-label">Name*</label>
<input type="text" class="form-control" id="name" name="name" required="" data-form-field="Name" placeholder="Name*">
</div>
</div>
<div class="col-xs-12">
<div class="form-group">
<label class="form-control-label">Email*</label>
<input type="email" class="form-control" id="email" name="email" required="" data-form-field="Email" placeholder="Email*">
</div>
</div>
<div class="col-xs-12">
<label class="form-control-label">Please leave a detailed message and include the type of project you have, as well as how extensive it is.</label>
<textarea class="form-control" id="message" name="message" rows="7" data-form-field="Message" placeholder="Please leave a detailed message and include the type of project you have, as well as how extensive it is."></textarea>
</div>
<div style="float: left;" class="g-recaptcha" data-sitekey="6LetWgITAAAAANNDaTINxoYz9xyOkp2rchwrQMbX"></div>
</div>
<div class="clear"></div>
<div class="form-separator"></div>
<div class="col-xs-12 col-md-8 col-md-offset-2 form-button-wrap">
<div class="text-xs-center text-md-right"><button type="submit" class="btn btn-lg btn-primary"><span class="fa fa-send mbr-iconfont mbr-iconfont-btn" style="color: rgb(255, 255, 255);"></span>Email Me</button></div>
</div>
</form>
I am handling the form using ajax, and I added captcha to decrease the chance of spam emails. The javascript/ajax, which is at the end of the html document is as follows:
<script type="text/javascript">
function validateEmail(email) {
var regex = /^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return regex.test(email);
}
$('form').submit(function(e) {
var getErrors = [];
e.preventDefault();
$(this).find('input').each(function(){
if($(this).val() == "" && $(this).is(':visible')) {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
} else {
$(this).removeClass('is-required');
}
if($(this).attr('id') == "email") {
var testEmail = $(this).val();
if(validateEmail(testEmail)){
$(this).removeClass('is-required');
} else {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
}
}
})
$(this).find('textarea').each(function(){
if($(this).val() == "") {
$(this).addClass('is-required');
getErrors.push($(this).attr('id'));
if($(this).hasClass('g-recaptcha-response')) {
$('.g-recaptcha').addClass('is-required')
}
} else {
$(this).removeClass('is-required');
if($(this).hasClass('g-recaptcha-response')) {
$('.g-recaptcha').removeClass('is-required')
}
}
})
if(getErrors.length < 1) {
$('.form-container form, .form-container .title').hide();
$('.form-container .sending').show();
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
var captcha = $('#g-recaptcha-response').val();
$.ajax({
type: "POST",
url: "captcha-lib.php",
data:{
"name": name,
"email": email,
"message": message,
"g-recaptcha-response": captcha
}
}).done(function(data){
$('.form-container .success').show();
$('.form-container .sending').hide();
}).fail(function(data){
$('.form-container .failed').show();
$('.form-container .sending').hide();
});
}
return false;
})
</script>
The captcha-lib.php file was originally in a folder along the path assets/php, where the assets folder was in the website root folder. I have since moved captcha-lib.php into the root folder, so that it is in the same location as the index.html file containing the ajax. Here is the code in captcha-lib.php:
<?php
header("Access-Control-Allow-Origin: https://www.google.com");
class ReCaptchaResponse
{
public $success;
public $errorCodes;
}
class ReCaptcha
{
private static $_signupUrl = "https://www.google.com/recaptcha/admin";
private static $_siteVerifyUrl =
"https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_2.0";
function ReCaptcha($secret)
{
if ($secret == null || $secret == "") {
die("To use reCAPTCHA you must get an API key from <a href='"
. self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
}
$this->_secret=$secret;
}
private function _encodeQS($data)
{
$req = "";
foreach ($data as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req=substr($req, 0, strlen($req)-1);
return $req;
}
private function _submitHTTPGet($path, $data)
{
$req = $this->_encodeQS($data);
$response = file_get_contents($path . $req);
return $response;
}
public function verifyResponse($remoteIp, $response)
{
// Discard empty solution submissions
if ($response == null || strlen($response) == 0) {
$recaptchaResponse = new ReCaptchaResponse();
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = 'missing-input';
return $recaptchaResponse;
}
$getResponse = $this->_submitHttpGet(
self::$_siteVerifyUrl,
array (
'secret' => $this->_secret,
'remoteip' => $remoteIp,
'v' => self::$_version,
'response' => $response
)
);
$answers = json_decode($getResponse, true);
$recaptchaResponse = new ReCaptchaResponse();
if (trim($answers ['success']) == true) {
$recaptchaResponse->success = true;
} else {
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = $answers [error-codes];
}
return $recaptchaResponse;
}
}
// your secret key
$secret = MY SECRET CAPTCHA KEY;
// empty response
$response = null;
// check secret key
$reCaptcha = new ReCaptcha($secret);
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$response = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($response != null && $response->success) {
// TODO change to jmceuen#shawsheencc.com
$email_to = "MYEMAILADDRESS"; // TODO - update when site is live
$noreply = "Me<MYEMAILADDRESS>"; // TODO - update when site is live
$autogreet = "Thank you for contacting me regarding my services! I will respond to your email as soon as I can. Please be patient in the meantime!\n";
$email_subject = "Me, Web Designer'";
$name = $_POST['name']; // required
$email = $_POST['email']; // required
$message = $_POST['message']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "".clean_string($message)."\n";
$email_message .= "".clean_string($name)."\n";
$email = $name.'<'.$email.'>';
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
} else {
header("HTTP/1.0 404 Not Found");
// TODO find a way to email an issue #mail("MYEMAILADDRESS", "There is an issue with php emailer", "The php resolved a 404. Please contact your web developer to resolve the issue.", "donotreply#scc.com");
}
?>
There seems to be something wrong with this documentation: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-authentication-HTTPPOST.html
I followed it exactly and it does seem to work. I always got SignatureDoesNotMatch error. v2 authorization works though. Makes me wonder if this some kind of Alpha-stage quality product.
Below is my php code. I tried to mimic the example in this page: http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
<?php
$secret = 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY';
$datenow = '20130806';
$region = 'us-east-1';
$service = 's3';
$terminator = 'aws4_request';
$policy = '{ "expiration": "2013-08-07T12:00:00.000Z",
"conditions": [
{"bucket": "examplebucket"},
["starts-with", "$key", "user/user1/"],
{"acl": "public-read"},
{"success_action_redirect": "http://examplebucket.s3.amazonaws.com/successful_upload.html"},
["starts-with", "$Content-Type", "image/"],
{"x-amz-meta-uuid": "14365123651274"},
["starts-with", "$x-amz-meta-tag", ""],
{"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/'.$datenow.'/'.$region.'/'.$service.'/'.$terminator.'"},
{"x-amz-algorithm": "AWS4-HMAC-SHA256"},
{"x-amz-date": "'.$datenow.'T000000Z" }
]
}';
$policy64 = base64_encode($policy);
assert($policy64 == $policy64);
$targetPolicy64 = 'eyAiZXhwaXJhdGlvbiI6ICIyMDEzLTA4LTA3VDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJleGFtcGxlYnVja2V0In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIka2V5IiwgInVzZXIvdXNlcjEvIl0sDQogICAgeyJhY2wiOiAicHVibGljLXJlYWQifSwNCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9leGFtcGxlYnVja2V0LnMzLmFtYXpvbmF3cy5jb20vc3VjY2Vzc2Z1bF91cGxvYWQuaHRtbCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJENvbnRlbnQtVHlwZSIsICJpbWFnZS8iXSwNCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LA0KICAgIFsic3RhcnRzLXdpdGgiLCAiJHgtYW16LW1ldGEtdGFnIiwgIiJdLA0KDQogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTMwODA2L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwNCiAgICB7IngtYW16LWFsZ29yaXRobSI6ICJBV1M0LUhNQUMtU0hBMjU2In0sDQogICAgeyJ4LWFtei1kYXRlIjogIjIwMTMwODA2VDAwMDAwMFoiIH0NCiAgXQ0KfQ==';
// echo base64_decode($targetPolicy64);
// echo $policy64."\n".$targetPolicy64;
assert($policy64 == $targetPolicy64);
// At this point everything seems to work well. Converting the policy
// to base64 resulted in exactly the same string with example.
// The problem, however, happens when calculating the signature,
// as shown below:
$targetSignature = '21496b44de44ccb73d545f1a995c68214c9cb0d41c45a17a5daeec0b1a6db047';
$signature = '';
$hash1 = hash_hmac(
'sha256',
$datenow,
"AWS4".$secret,
true
);
$hash2 = hash_hmac(
'sha256',
$region,
$hash1,
true
);
$hash3 = hash_hmac(
'sha256',
$service,
$hash2,
true
);
$signingKey = hash_hmac(
'sha256',
$terminator,
$hash3,
true
);
$signature = base64_encode(hash_hmac(
'sha256',
$policy64,
$signingKey,
true
));
echo $signature."\n".$targetSignature;
// This assertion never passed.
assert($signature == $targetSignature);
I thought it was the problem of the example so I tried creating a sample browser upload page with exactly the same methods, but it did not work either.
Running the signature signing code here: PHP hash_hmac not matching AWS Signature 4 example however, works, so I doubt the issue is during signature creation, or is it?
Please help, anyone.
<?php
// Fill These In!
define('S3_BUCKET', '');
define('S3_KEY', '');
define('S3_SECRET', '');
define('S3_REGION', ''); // S3 region name: http://amzn.to/1FtPG6r
define('S3_ACL', 'private'); // File permissions: http://amzn.to/18s9Gv7
// Stop Here
$algorithm = "AWS4-HMAC-SHA256";
$service = "s3";
$date = gmdate('Ymd\THis\Z');
$shortDate = gmdate('Ymd');
$requestType = "aws4_request";
$expires = '86400'; // 24 Hours
$successStatus = '201';
$scope = [
S3_KEY,
$shortDate,
S3_REGION,
$service,
$requestType
];
$credentials = implode('/', $scope);
$policy = [
'expiration' => gmdate('Y-m-d\TG:i:s\Z', strtotime('+6 hours')),
'conditions' => [
['bucket' => S3_BUCKET],
['acl' => S3_ACL],
[
'starts-with',
'$key',
''
],
['success_action_status' => $successStatus],
['x-amz-credential' => $credentials],
['x-amz-algorithm' => $algorithm],
['x-amz-date' => $date],
['x-amz-expires' => $expires],
]
];
$base64Policy = base64_encode(json_encode($policy));
// Signing Keys
$dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . S3_SECRET, true);
$dateRegionKey = hash_hmac('sha256', S3_REGION, $dateKey, true);
$dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
$signingKey = hash_hmac('sha256', $requestType, $dateRegionServiceKey, true);
// Signature
$signature = hash_hmac('sha256', $base64Policy, $signingKey);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Direct Upload Example</title>
<style>
.progress {
position: relative;
width: 100%;
height: 15px;
background: #C7DA9F;
border-radius: 10px;
overflow: hidden;
}
.bar {
position: absolute;
top: 0; left: 0;
width: 0; height: 15px;
background: #85C220;
}
.bar.red { background: tomato; }
</style>
</head>
<body>
<!-- Direct Upload to S3 -->
<!-- URL prefix (//) means either HTTP or HTTPS (depending on which is being currently used) -->
<form action="//<?php echo S3_BUCKET . "." . $service . "-" . S3_REGION; ?>.amazonaws.com"
method="POST"
enctype="multipart/form-data"
class="direct-upload">
<!-- Note: Order of these is Important -->
<input type="hidden" name="key" value="${filename}">
<input type="hidden" name="acl" value="<?php echo S3_ACL; ?>">
<input type="hidden" name="success_action_status" value="<?php echo $successStatus; ?>">
<input type="hidden" name="policy" value="<?php echo $base64Policy; ?>">
<input type="hidden" name="X-amz-algorithm" value="<?php echo $algorithm; ?>">
<input type="hidden" name="X-amz-credential" value="<?php echo $credentials; ?>">
<input type="hidden" name="X-amz-date" value="<?php echo $date; ?>">
<input type="hidden" name="X-amz-expires" value="<?php echo $expires; ?>">
<input type="hidden" name="X-amz-signature" value="<?php echo $signature; ?>">
<input type="file" name="file">
<!-- Progress Bar to show upload completion percentage -->
<div class="progress"><div class="bar"></div></div>
</form>
<!-- Used to Track Upload within our App -->
<form action="server.php" method="POST">
<input type="hidden" name="upload_original_name" id="upload_original_name">
<label for="upload_custom_name">Name:</label><br />
<input type="text" name="upload_custom_name" id="upload_custom_name"><br />
<input type="submit" value="Save"/>
</form>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="fileupload/jquery.fileupload.js"></script>
<script>
$(document).ready(function () {
$('.direct-upload').each(function () {
var form = $(this);
form.fileupload({
url: form.attr('action'),
type: 'POST',
datatype: 'xml',
add: function (event, data) {
// Message on unLoad.
// Shows 'Are you sure you want to leave message', just to confirm.
window.onbeforeunload = function () {
return 'You have unsaved changes.';
};
// Actually submit to form, sending the data.
data.submit();
},
progress: function (e, data) {
// This is what makes everything really cool, thanks to that callback
// you can now update the progress bar based on the upload progress.
var percent = Math.round((data.loaded / data.total) * 100);
$('.bar').css('width', percent + '%');
},
fail: function (e, data) {
// Remove the 'unsaved changes' message.
window.onbeforeunload = null;
$('.bar').css('width', '100%').addClass('red');
},
done: function (event, data) {
window.onbeforeunload = null;
// Fill the name field with the file's name.
$('#upload_original_name').val(data.originalFiles[0].name);
$('#upload_custom_name').val(data.originalFiles[0].name);
}
});
});
});
</script>
</body>
</html>
(https://www.designedbyaturtle.co.uk/2015/direct-upload-to-s3-using-aws-signature-v4-php/)
Works for me
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 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.