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
Related
Can't seem to get the Google invisible reCAPTCHA to work. This should be easy, looking to find out what I'm doing wrong. Here's my client side code:
<head>
<script type="text/javascript">
var onSubmit = function(token) {
console.log('success!');
};
var onloadCallback = function() {
grecaptcha.render('submit', {
'sitekey' : '------my site key---------',
'callback' : onSubmit
});
};
</script>
</head>
Form:
<form action='/mail-script.php' target='_self' method='POST' id='econtact'>
<input class='w3-input' type='text' placeholder='Name' required name='Name'>
<input class='w3-input w3-section' type='text' placeholder='Email' required name='Email'>
<input class='w3-input w3-section' type='text' placeholder='Subject' required name='Subject'>
<input class='w3-input w3-section' type='text' placeholder='Comment' required name='Comment'>
<button class='w3-button w3-dark-blue w3-section' type='submit' name='submit'>
<i class='fa fa-paper-plane'></i> SEND MESSAGE</button></form>
<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async defer></script>
Serve side code:
<?php
function checkCaptcha(){
if(isset($_POST['g-recaptcha-response'])){
$captcha = $_POST['g-recaptcha-response'];
$postdata = http_build_query(
array(
'secret' => '----------secret code----------',
'response' => $captcha,
'remoteip' => $_SERVER['REMOTE_ADDR']
)
);
$options = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context));
return $result->success;
}else{
return false;
}
}
$captcha_result = checkCaptcha();
echo("the captcha result is: " . $captcha_result);
?>
So $captcha_result is blank. I can't get it to detect anything. I get the sense
g-recaptcha-response isn't being passed through the form correctly, or something else is going on. Thanks for the help.
UPDATE: var_dump($result); = NULL
Want to create a simple form to send the values and image to database, below is the php code -
Created two php file process_upload and connection
processs_upload.php
<?php
require 'connection.php';
$conn = Connect();
$name=$conn->real_escape_string($_POST['name']);
$mobile_number=$conn->real_escape_string($_POST['mobile_number']);
$email_id=$conn->real_escape_string($_POST['email_id']);
$type=$conn->real_escape_string($_POST['type']);
$query = "INSERT into tb_cform (name,mobile_number,email_id,type) VALUES('" . $name . "','" . $mobile_number . "','" . $email_id . "','" . $type . "')";
if ( 0 < $_FILES['image_file']['error'] ) {
echo 'Error: ' . $_FILES['image_file']['error'] . '<br>';
}
else{
$time=time();
if(($type=='image/png') || ($type=='image/gif') || ($type=='image/jpeg') || ($type=='image/pjpeg') || ($type=='image/jpg')){ //if file is image
if(move_uploaded_file($_FILES['image_file']['tmp_name'], 'pictures/'.$time.'_'.$_FILES['image_file']['name'])){
echo 'done ';
}else{
echo 'image error';
}
}else{//if file is video
if(move_uploaded_file($_FILES['image_file']['tmp_name'], 'videos/'.$time.'_'.$_FILES['image_file']['name'])){
echo 'done';
}else{
echo 'video error';
}
}
}
$conn->close();
?>
connection.php
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "";
$dbname = "database";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
Created a table in phpmyadmin and below is the table -
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
CREATE TABLE IF NOT EXISTS `tb_cform` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`name` text CHARACTER SET utf8 NOT NULL,
`mobile_number` int(11) NOT NULL,
`email_id` text NOT NULL,
`type` longblob NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
HTML form
<!DOCTYPE HTML>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="Boomer" />
<title>Uploader</title>
<link href="css/upload_css.css" media="screen" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.form.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var optionsH = {
target: '#H_output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmitH, // pre-submit callback
uploadProgress: OnProgressH,
error: onerrorH,
success: afterSuccessH, // post-submit callback
resetForm: true // reset the form after successful submit
};
$('#MyUploadFormH').submit(function(){
var name=$("#name").val();
var mobile_number=$("#mobile_number").val();
var email_id=$("#email_id").val();
if((name!='') && (mobile_number!='') && (email_id!='')){
$('#MyUploadFormH').attr("action","process_upload.php");
$(this).ajaxSubmit(optionsH);
// return false to prevent standard browser submit and page navigation
return false;
}else{
$("#H_output").html("All field are required");
}
});
function beforeSubmitH(){
//check whether browser fully supports all File API
if (window.File && window.FileReader && window.FileList && window.Blob)
{
if(!$('#imageInputH').val()) //check eHty input filed
{
$("#H_output").html("select picture or video to upload");
return false
}else{
$("#H_output").html("file selected");
}
var fsize = $('#imageInputH')[0].files[0].size; //get file size
var ftype = $('#imageInputH')[0].files[0].type; // get file type
switch(ftype)
{
case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': case 'video/mp4': case 'video/3gp': case 'video/avi': case 'video/mkv':
case 'video/flv': case 'video/wmv': case 'video/ovb': case 'video/ogg':
break;
default:
$("#H_output").html("<b>"+ftype+"</b> Unsupported file type!");
return false
}
//Allowed file size is less than 1 MB (1048576)
if(fsize>10485760)
{
$("#H_output").html("<b>"+bytesToSize(fsize) +"</b> is too big! <br />Please reduce the size and try again.");
return false
}
document.getElementById("header_submit-btn").setAttribute("disabled", true);
$("#H_output").html("");
}
else
{
//Output error to older unsupported browsers that doesn't support HTML5 File API
$("#H_output").html("Please upgrade your phone!");
return false;
}
}
function OnProgressH(){
$("#upload_formH").hide();
$("#upload_loader_header").show();
}
//when error occur
function onerrorH(){
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
$("#H_output").html("connection error...");
//$('#staff_bfr_uplad_prv_cnt').html("");
//progressboxH.hide();
//$('#MyUploadForm').resetForm();
$("#upload_formH").show();
$("#upload_loader_header").hide();
}
//after succesful upload
function afterSuccessH()
{
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
$("#upload_formH").show();
$("#upload_loader_header").hide();
var logo_thumb=$("#header_pix_location").html();
$("img[id^='eml_header_logo']").attr('src',dp_thumb);
}
document.querySelector('#H_fileSelect').addEventListener('click', function(e){
var fileInput = document.querySelector('#imageInputH');
//clickH(fileInput); // Simulate the click with a custom event.
fileInput.click(); // Or, use the native click() of the file input.
$("#H_output").html("");
}, false);
$("#imageInputH").change(function(){
var fsize = $('#imageInputH')[0].files[0].size; //get file size
var ftype = $('#imageInputH')[0].files[0].type; // get file type
if(fsize>10485760){
$("#H_output").html("<b>"+bytesToSize(fsize) +"</b> is too big! <br />Please reduce the size and try again.");
document.getElementById("header_submit-btn").setAttribute("disabled", true);
}else{
$("#type").val(ftype);
$("#H_output").html("<span style='color: green;'>file selected</span>");
document.getElementById("header_submit-btn").removeAttribute("disabled", true);
}
});
//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
</script>
</head>
<body>
<div id="add_cpp_form">
<center>
<div style="float: none; width: 270px; padding: 10px;" id="upload_formH">
<form onSubmit="return false" method="post" enctype="multipart/form-data" id="MyUploadFormH">
<input type="text" class="form_input" id="name" name="name" value="" placeholder="Name" />
<input type="text" class="form_input" id="mobile_number" name="mobile_number" value="" placeholder="Mobile Number" />
<input type="text" class="form_input" id="email_id" name="email_id" value="" placeholder="Email Id" />
<input name="image_file" id="imageInputH" type="file" />
<input name="type" id="type" type="hidden" />
<input type="submit" id="header_submit-btn" class="effect1 ripple" value="Submit" />
<div id="H_fileSelect" class="effect1 ripple" style="border-radius: 0px;">Select</div>
<img src="images/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="H_output"></div>
</div>
<div id="upload_loader_header" style="float: left; display: none; text- align: center; width: 100%;">
<img style="float: none;" src="img/ajax-loader.gif" width="32" height="32" />
</div>
</center>
</div>
</body>
</html>
Now when i am running the code I am getting image error and video error message, the connection is successfully done but getting the message.
Try grant permissions as in
suppose your code are under /var/www/my_project
try chmod -R 664 /var/www/my_project.
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.
I am working on a self-learning project to learn how to use Laravel 4. At this point, I have managed to get most of it to work, but the problem I run into is I get 2 entries in the database tables rather than 1.
I had an error before about a duplicate primary key value, and it still added two entries. I thought this error was the reason behind the duplicate values, but I have since fixed this error and this still happens.
I'm sorry if my code is really messy and unorganized. I will be reorganizing it at the end.
Here's my code (I can't submit images):
Thanks for the help!
File 1: views/customer/index.blade.php
#extends('layout')
<?php
$total = "";
$url = "";
function line_totals()
{
$qty = "";
$unit_price = "";
global $total;
$bool = isset($_GET['qty']) || isset($_GET['unit_price']);
if($bool)
{
$qty = $_GET['qty'];
$unit_price = $_GET['unit_price'];
}
$qty = str_replace("\n", '<br>', $qty);
$qty = str_replace("\n", '<br>', $qty);
$unit_price = str_replace("\n", '<br>', $unit_price);
$unit_price = str_replace("\n", '<br>', $unit_price);
$qtyArr = explode('<br>', $qty);
$priceArr = explode('<br>', $unit_price);
$total = array();
for($i = 0; $i < count($qtyArr); $i++)
{
$total[$i] = $qtyArr[$i] * $priceArr[$i];
}
return $total;
}
$total = json_encode(line_totals());
function insert_customer()
{
$customerIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['name']) || isset($_GET['address']) || isset($_GET['city']) || isset($_GET['state']) || isset($_GET['zip']);
if($customerIsFilled)
{
$id = "";
$name = $_GET['name'];
$address = $_GET['address'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
$created_at = date('Y-m-d H:i:s');
$updated_at = date('Y-m-d H:i:s');
$insert_cust = array(
'id' => $id,
'name' => $name,
'address' => $address,
'city' => $city,
'state' => $state,
'zip' => $zip,
'created_at' => $created_at,
'updated_at' => $updated_at
);
DB::table('customer')->insert($insert_cust);
}
else
return;
}
function insert_work()
{
$curId = 0;
$select = DB::select('SELECT * FROM customer');
$ids = array();
for($i = 0; $i < count($select); $i++)
{
if(!empty($select))
{
$ids[$i] = DB::table('customer')->pluck('id');
$curId = max($ids);
}
}
$workIsFilled = isset($_GET['date']) || isset($_GET['receipt']) || isset($_GET['qty']) || isset($_GET['description']) || isset($_GET['unit_price']) || isset($_GET['line_total']) || isset($_GET['created_at']) || isset($_GET['updated_at']);
$line_total = "";
if($workIsFilled)
{
$cust_id = $curId;
$qty = htmlspecialchars($_GET['qty']);
$date = htmlspecialchars($_GET['date']);
$receipt = htmlspecialchars($_GET['receipt']);
$description = htmlspecialchars($_GET['description']);
$unit_price = htmlspecialchars($_GET['unit_price']);
$created_at = date('Y-m-d H:i:s');
$updated_at = date('Y-m-d H:i:s');
$tot = line_totals();
for($i = 0; $i < count($tot); $i++)
{
$line_total .= $tot[$i]."\n";
}
$insert_work = array(
'cust_id' => $cust_id,
'qty' => $qty,
'date' => $date,
'receipt' => $receipt,
'description' => $description,
'unit_price' => $unit_price,
'line_total' => $line_total,
'created_at' => $created_at,
'updated_at' => $updated_at
);
DB::table('work')->insert($insert_work);
}
else
return;
}
// Store HTTP GET request parameters into $url
$get = action('CustomerController#getResults', $url);
?>
#section('content')
<form action="{{ $url }}" method="get">
<table style="margin-left:250px;" cellspacing="5">
<tr>
<td> Name: </td> <td> <input name="name" id="name" type="text" value="John Doe"> </td>
<td> Address: </td> <td> <input name="address" id="address" type="text" value="Street Address"> </td>
<td> City: </td> <td> <input name="city" id="city" type="text" value="City"> </td>
<td> ST: </td> <td> <input name="state" id="state" size="2" maxlength="2" type="text" value="ST"> </td>
<td> Zip: </td> <td> <input name="zip" id="zip" type="text" value="12345"> </td>
</tr>
</table>
<br><br>
<h1 style="text-align:center;">Work Performed</h1>
<table style="margin-left:350px;" cellspacing="5">
<tr>
<td> Date: </td> <td> <input id="date" name="date" type="text" value="14-01-01"></td>
<td> Receipt#: </td> <td> <input name="receipt" value="9000"> </td>
</tr>
</table>
<table style="margin-left:350px;" cellspacing="5">
<tr>
<td> <textarea rows="1" placeholder="Qty" id="qty" name="qty">5<?php echo "\n"; ?>5</textarea> </td>
<td> <textarea rows="1" placeholder="Description" id="description" name="description">Job 1<?php echo "\n"; ?>Job 2</textarea> </td>
<td> <textarea rows="1" placeholder="Unit Price" id = "unit_price" name="unit_price">200<?php echo "\n"; ?>400</textarea> </td>
<td> <textarea rows="1" placeholder="Line Total" id="line_total" name="line_total" disabled></textarea> </td>
</tr>
</table>
<br>
<input style="margin-left:600px;" id="add" type="submit" value="Submit">
</form>
#stop
File 2: views/layout.blade.php
<!doctype html>
<html>
#section('header')
<head>
<title></title>
<style type="text/css">
#subHeading
{
display: block;
position: absolute;
font-style: italic;
font-weight: bold;
font-size: 25pt;
margin-top:-10px;
margin-left: 600px;
}
#qty, #description, #unit_price, #line_total
{
text-align: center;
}
</style>
<link rel="stylesheet" type="text/css" href="css/ui-lightness/jquery-ui.min.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
</head>
<body>
<span id="subHeading">Invoice</span>
<br>
<hr
<br>
<script type="text/javascript">
$(function(){
$("#date").datepicker({
dateFormat:"y-mm-dd"
});
});
$(document).ready(function(){
if($("#name").val() != "" && $("#address").val() != "" && $("#city").val() != "" && $("#state").val() != "" && $("#zip").val() != "")
{
$("#add").on('click', function()
{
$.ajax({
url: 'customer/index.blade.php',
success: $(function(){
//alert("New Customer!");
<?php insert_customer();?>
})
});
});
}
else if($("#qty").val() != "" && $("#description").val() != "" && $("#unit_price").val() != "")
{
$("#add").on('click', function()
{
$.ajax({
url: 'customer/index.blade.php',
success: $(function(){
//alert("New Work Order Added!");
<?php insert_work(); ?>
})
});
});
}
$("#line_total").hide();
});
/* $.ajax({
url: 'index.blade.php',
success: $(function(data) {
// <?php insert_customer(); ?>
<?php insert_work(); ?>
});*/
</script>
#stop
#yield('header')
#yield('content')
</body>
</html>
Ok so the reason you're getting a double insert is the commented out javascript contains php functions that aren't commented out:
/* $.ajax({
url: 'index.blade.php',
success: $(function(data) {
// <?php insert_customer(); ?>
<?php insert_work(); ?>
});*/
While you've managed to comment out the javascript here, the php will still run. To successfully comment out the php you'd need to work within the php tags:
<?php // myFunction(); ?>
<?php /* myFunction(); */ ?>
From looking over your code it looks like you just need to work on your understanding of Javascript (a client side language) vs PHP (a server side language) which is no problem, that's what makes a learning project so valuable. Here's a bit of info you'll hopefully find useful:
1. PHP function calls in the page will be called on page load. Here's an example:
An example php file:
<?php
function myFunction(){
echo 'Hello World';
}
?>
<html>
<body>
<?php myFunction(); ?>
</body>
</html>
This will output the following html to the browser:
<html>
<body>
Hello World
</body>
</html>
So when you call your <?php insert_work(); ?> function in the page, it will run straight away on the page load and because it's in there twice you're getting duplicate calls of your function.
2. You can't directly call PHP functions from Javascript
This unfortunately wont work how you might want it to:
<?php
function myPhpFunction(){
// Insert into database on click
}
?>
<html>
<head>
<script>
$('.button').click(function(){
<?php myPhpFunction(); ?>
});
</script>
</head>
...
What actually happens here is the myPhpFunction() get's called on the page load. What you need is an ajax call which I can see you already have attached to your #add submit button. Here's a quick example using your code:
A brief version of your layout.blade.php
<html>
<head>
<script>
$("#add").on('click', function()
{
// Grab the form data
var data = $("form").serialize();
// Perform the ajax request
$.ajax({
// Call the route here not the file
url: '/customer',
data: data,
success: $(function(data){
// Add the returned data to the p tag
$("p").html(data);
})
});
});
</script>
</head>
<body>
<form action="{{ $url }}" method="get">
<input name="name" id="name" type="text" value="John Doe">
<textarea rows="1" placeholder="Description" id="description" name="description">
<input id="add" type="submit" value="Submit">
</form>
<p><!-- Your results will load here --></p>
</body>
</html>
A brief version of your customer/index.blade.php
<?php
function insert_customer(){
// Perform DB insert
echo 'Success! Customer added.';
}
// Call insert_customer()
insert_customer();
?>
Here when your button is clicked we grab the form data and send a ajax GET request to the customer/index route which performs the function and send us the feedback that the function has been successful.
Sorry that's such a lengthy answer. Hopefully it's helpful!
this is my first time in using recaptcha on my website.
I'm using PHP API to validate the recaptcha, it keeps saying invalid-request-cookie
I found out on different forum that www.example.com is different with example.com, so I register my site again without www , but still it is not working..
When I verify the recaptcha_response_field and recaptcha_challenge_field the values are correct.
here is the captcha checker:
require_once(recaptchalib.php');
$publickey = "not displayed"; //for security
$privatekey = "not displayed"; //for security
$error = null;
if( $_POST ) {
$arr = array('a' => $_POST['task'], 'b' => $_POST['recaptcha_challenge_field'], 'c' => $_POST['recaptcha_response_field']);
if( trim($arr['a']) == 'captcha' ) {
$resp = null;
$error = null;
$captcha_result = 'success';
$resp = recaptcha_check_answer( $privatekey, $_SERVER["REMOTE_ADDR"], $arr['b'], $arr['c'] );
if( $resp->error ){
$captcha_result = 'fail';
}
echo $captcha_result;
}
}
here is the HTML code:
<div id="captcha-div">
<script type="text/javascript">
var RecaptchaOptions = {
tabindex: 1,
theme: 'custom',
custom_theme_widget: 'recaptcha_widget'
};
</script>
<div id="recaptcha_widget" style="display:none"><div id="recaptcha_image" style="width: 200px; height: 57px; "></div>
<?php echo recaptcha_get_html($publickey, $error); ?>
<div class="recaptcha_only_if_incorrect_sol" style="color:red">Incorrect. Try Again.</div>
<span class="recaptcha_only_if_audio">Type what you hear</span>
<input type="text" id="recaptcha_response_field" name="recaptcha_response_field">
<div class="recaptcha_only_if_audio">Kumuha ng larawang CAPTCHA</div>
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=6Le_X88SAAAAAAH3NEbkIr3w75SEQnQYwl96Y7f0"></script>
<noscript><iframe src="http://www.google.com/recaptcha/api/noscript?k=6Le_X88SAAAAAAH3NEbkIr3w75SEQnQYwl96Y7f0" height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field" value="manual_challenge"></noscript></div>
<script type="text/javascript">
window.onload = function() {
Recaptcha.focus_response_field();
}
</script>
<p id="captcha-error" style="color:red; font-weight:bold;"></p>
</div>
<div><a id="captcha-refresh" href="javascript:Recaptcha.reload()"></a></div>
<div class="recaptcha_only_if_image"><a id="captcha-audio" href="javascript:Recaptcha.switch_type('audio')"></a></div>
<div><a id="captcha-help" href="javascript:Recaptcha.showhelp()"></a></div>
<div id="circle-submit"></div>
can anyone help me out with this issue?
Thanks,
Justin
As reCAPTCHA Support says:
No, this will not result in the invalid domain. What this means is that you are not submitting the recaptcha_challenge_field to the server correctly.
So make sure you rendering the form with recapcha corectly. Check out this link.