Android - notification when field in database changes - php

I am pretty new to programming.
I am making an application for android that gets data about events from database, users may add new events, but they have "status" set as 0, so I have to change them in phpmyadmin to 1 to make them show as listviews in MainActivity. Everything's done via php and json.
I want to make some sort of notifications, when a new event gets it's status changed to 1 in database then notification is send to all people who have the application. What is the best approach? Did I describe everything clearly?
I was looking through the internet and found something about GCM, but I am lost and I don't know where to start. Do you have perhaps some tutorial to achieve what I want?

So to send a notification on go-ahead phrase changes, i created this php file:
<?php
define("servername","your_servername");
define("username","your_username");
define("password","your_password");
define("dbname","your_dbname");
define( 'API_ACCESS_KEY', your_API_Key' );
$topic = "/topics/todos";
$url = 'https://fcm.googleapis.com/fcm/send';
$exists=0;
$frasenova=$_POST['frase'];
$autornovo=$_POST['autor'];
$conn =new mysqli(servername, username, password, dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$sqlquery="SELECT * FROM frase_dia WHERE id='1'";
$stmt=$conn->prepare($sqlquery);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $frase, $autor);
while($stmt->fetch())
{
$exists=$exists+1;
}
if($exists==1){
//if row exists
$sqlupdate="UPDATE frase_dia SET frase='".$frasenova."', autor='".$autornovo."' WHERE id='1'";
$stmt=$conn->prepare($sqlupdate) or trigger_error($conn->error, E_USER_ERROR);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
//notification
$fields = array (
'to' => $topic,
'notification' => array (
"body" => $frasenova."\n\n".$autornovo,
"title" => "Frase do dia",
"sound"=> "default"
),
'data' => array(
"frase" => $frasenova,
"autor"=> $autornovo,
"tiponotificacao"=> 1
)
);
}else{
//if row not exists
$sqlnew="INSERT INTO frase_dia (frase, autor) VALUES ('$frasenova','$autornovo')";
$stmt=$conn->prepare($sqlnew) or trigger_error($conn->error, E_USER_ERROR);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
echo 'adicionado (novo)';
//notification
$fields = array (
'to' => $topic,
'notification' => array (
"body" => $frasenova."\n\n".$autornovo,
"title" => "Frase do dia",
"sound"=> "default",
"click_action"=> "inicio"
),
'data' => array(
"frase" => $frasenova,
"autor"=> $autornovo,
"tiponotificacao"=> 1
)
);
}
$fields = json_encode ( $fields );
$headers = array (
'Authorization: key=' . API_ACCESS_KEY,
'Content-Type: application/json'
);
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_POST, true );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
$result = curl_exec ( $ch );
curl_close ( $ch );
echo'<div>
<svg style="width:48px;height:48px" viewBox="0 0 24 24">
<path fill="#a62a2a" d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />
</svg>
<br>
<font size="+2">';
echo 'Conteúdo adicionado';
echo'</font>
<br><br>
</div>';
}
?>
And this HTML file:
<html>
<head>
<meta charset="utf-8">
<title>Frase do dia</title>
<!--Import Google Icon Font-->
<link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="css/materialize.min.css" media="screen,projection"/>
<!--Let browser know website is optimized for mobile-->
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
/* label focus color */
.input-field input[type=text]:focus + label {
color: #a62a2a;
}
/* label underline focus color */
.input-field input[type=text]:focus {
border-bottom: 1px solid #a62a2a;
box-shadow: 0 1px 0 0 #a62a2a;
}
.input-field textarea[class=materialize-textarea]:focus + label {
color: #a62a2a;
}
.input-field textarea[class=materialize-textarea]:focus {
border-bottom: 1px solid #a62a2a;
box-shadow: 0 1px 0 0 #a62a2a;
}
</style>
</head>
<body bgcolor="#F2F2F2">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="js/materialize.min.js"></script>
<div style="margin-left:20%; margin-right:20%; background-color:#FFF; border-radius:5px; margin-bottom:25px;">
<h1 style="text-align:center; padding-top:10px;">Frase do dia</h1>
<div class="row">
<form class="col s12" action="adicionar_frase.php" method="post">
<div class="row">
<div class="input-field col s12">
<input id="frase" type="text" name="frase" required>
<label for="frase">Frase</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="autor" type="text" name="autor" required>
<label for="autor">Autor</label>
</div>
</div>
<button style="display:block; margin:auto" class="btn waves-effect waves-light red darken-3" type="submit" name="Adicionar">Adicionar
</button>
</form>
</div>
<div style="width:100%; height:5px;"></div>
</div>
</body>
</html>
So what i do is send the form data in HTML file to the php file and in php file change the phrase in mysql database table and if change is sucessfully i create and send nottification to my users.
You can adapt these code to your Project any question just ask.

Related

How to Include Files by ID: MY shop the LAST Setting

My website the products are identified by the msql id that dynamically loads each page
<?php
session_start();
require_once('./inc/config.php');
require_once('./inc/helpers.php');
if(isset($_GET['product']) && !empty($_GET['product']) && is_numeric($_GET['product']))
{
$sql = "SELECT p.*,pdi.img from tenis_femininos p
INNER JOIN tenis_feminios_images pdi ON pdi.product_id = p.id WHERE pdi.is_featured =:featured AND p.id =:productID";
$handle = $db->prepare($sql);
$params = [
':featured'=>1,
':productID' =>$_GET['product'],
];
$handle->execute($params);
if($handle->rowCount() == 1 )
{
$getProductData = $handle->fetch(PDO::FETCH_ASSOC);
$imgUrl = PRODUCT_IMG_URL.str_replace(' ','-',strtolower($getProductData ['sku']))."/".$getProductData ['img'];
}
else
{
$error = '404! No record found';
}
}
else
{
$error = '404! No record found';
}
if(isset($_POST['add_to_cart']) && $_POST['add_to_cart'] == 'add to cart')
{
$productID = intval($_POST['product_id']);
$productQty = intval($_POST['product_qty']);
$entraSku = validate_input($_POST['pega_sku']);
$entraCor = validate_input($_POST['pega_cor']);
$entraSize = validate_input($_POST['pega_size']);
$sql = "SELECT p.*,pdi.img from tenis_femininos p
INNER JOIN tenis_feminios_images pdi ON pdi.product_id = p.id WHERE pdi.is_featured =:featured AND p.id =:productID";
$prepare = $db->prepare($sql);
$params = [
':featured'=>1,
':productID' =>$productID,
];
$prepare->execute($params);
$fetchProduct = $prepare->fetch(PDO::FETCH_ASSOC);
$calculateTotalPrice = number_format($productQty * $fetchProduct['price'],2);
$cartArray = [
'product_id' =>$productID,
'qty' => $productQty,
'sku' => $entraSku,
'color' => $entraCor,
'medida' => $entraSize,
'product_name' =>$fetchProduct['product_name'],
'product_price' => $fetchProduct['price'],
'total_price' => $calculateTotalPrice,
'product_img' =>$fetchProduct['img']
];
if(isset($_SESSION['cart_items']) && !empty($_SESSION['cart_items']))
{
$productIDs = [];
foreach($_SESSION['cart_items'] as $cartKey => $cartItem)
{
$productIDs[] = $cartItem['product_id'];
if($cartItem['product_id'] == $productID)
{
$_SESSION['cart_items'][$cartKey]['qty'] = $productQty;
$_SESSION['cart_items'][$cartKey]['sku'] = $entraSku;
$_SESSION['cart_items'][$cartKey]['color'] = $entraCor;
$_SESSION['cart_items'][$cartKey]['medida'] = $entraSize;
$_SESSION['cart_items'][$cartKey]['total_price'] = $calculateTotalPrice;
break;
}
}
if(!in_array($productID,$productIDs))
{
$_SESSION['cart_items'][]= $cartArray;
}
$successMsg = true;
}
else
{
$_SESSION['cart_items'][]= $cartArray;
$successMsg = true;
}
}
$pageTitle = 'Cool T-Shirt Shop Single Product Page';
$metaDesc = 'Demo PHP shopping cart get tenis_femininos from database';
?>
<!DOCTYPE html>
<html lang="pt-br"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="shortcut icon" href="https://glarza.com/favicon.ico.webp" type="image/x-icon"/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons#1.3.0/font/bootstrap-icons.css">
<title><?php echo (isset($pageTitle)?$pageTitle:'PHP Shopping Cart')?></title>
<meta name="description" content="<?php echo (isset($metaDesc)?$metaDesc:'Demo PHP Shopping Cart')?>">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript" src="https://cdn.stormize.com/framework/99571.js"></script><!--<![endif]-->
<script type="text/javascript">
<!-- FUCTION PELO TYPE BUTTON --><!-- FUCTION PELO TYPE BUTTON --><!-- FUCTION PELO TYPE BUTTON --><!-- FUCTION PELO TYPE BUTTO
//-->
function switchVisible() {}
</script>
<style type="text/css">
#selectable img {
margin: 5px;
padding: 5px;
border: 2px solid #ffffff;
}
.selected-items {
border: 2px solid #ff0000;
line-height: 32px;
}
</style>
</head>
<body>
<div class="container">
<div class="row mt-2 mb-2">
<div class="col-md-12 col-xs-12">
<h1>
Cool T-Shirt Shop
</h1>
</div>
</div>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<ul class="navbar-nav mr-auto mt-2 mt-lg-0">
</ul>
<div class="form-inline my-2 my-lg-0">
</div>
</nav>
<?php //ESTE É O PHP DO CHECKOUT COM ALGUMA MODIFICAÇÕES PRA FUNCIONAR AQUI;
//pre($_SESSION);
if(isset($_POST['submit']))
{
if(isset($_POST['first_name'],$_POST['last_name'],$_POST['email'],$_POST['rua'],$_POST['bairro'],$_POST['cidade'],$_POST['uf']) && !empty($_POST['first_name']) && !empty($_POST['last_name']) && !empty($_POST['email']) && !empty($_POST['rua']) && !empty($_POST['bairro']) && !empty($_POST['cidade']) && !empty($_POST['uf']))
{
$firstName = $_POST['first_name'];
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) == false)
{
$errorMsg[] = 'Please enter valid email address';
}
else
{
//validate_input is a custom function
//you can find it in helpers.php file
$firstName = validate_input($_POST['first_name']);
$lastName = validate_input($_POST['last_name']);
$email = validate_input($_POST['email']);
$telefone = validate_input($_POST['telefone']);
$cep = validate_input($_POST['cep']);
$rua = validate_input($_POST['rua']);
$numero = validate_input($_POST['numero']);
$complemento = validate_input($_POST['complemento']);
$bairro = validate_input($_POST['bairro']);
$cidade = validate_input($_POST['cidade']);
$uf = validate_input($_POST['uf']);
$sql = 'insert into orders (first_name, last_name, email, telefone, cep, rua, numero, complemento, bairro, cidade, uf, order_status,created_at, updated_at) values (:fname, :lname, :email, :telefone, :cep, :rua, :numero, :complemento, :bairro, :cidade, :uf, :order_status,:created_at, :updated_at)';
$statement = $db->prepare($sql);
$params = [
'fname' => $firstName,
'lname' => $lastName,
'email' => $email,
'telefone' => $telefone,
'cep' => $cep,
'rua' => $rua,
'numero' => $numero,
'complemento' => $complemento,
'bairro' => $bairro,
'cidade' => $cidade,
'uf' => $uf,
'order_status' => 'confirmed',
'created_at'=> date('Y-m-d H:i:s'),
'updated_at'=> date('Y-m-d H:i:s')
];
$statement->execute($params);
if($statement->rowCount() == 1)
$pageTitle = 'Demo PHP Shopping cart checkout page with Validation';
$metaDesc = 'Demo PHP Shopping cart checkout page with Validation';
?>
<?php if(isset($getProductData) && is_array($getProductData)){?>
<?php if(isset($successMsg) && $successMsg == true){?>
<div class="row mt-3">
<div class="col-md-12">
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert">×</button>
<img src="<?php echo $imgUrl ?>" class="rounded img-thumbnail mr-2" style="width:40px;"><?php echo $getProductData['product_name']?> is added to cart. View Cart
</div>
</div>
</div>
<?php }?>
<div class="row mt-3">
<div class="col-md-5">
<img src="<?php echo $imgUrl;?>">
</div>
<div class="col-md-7">
<h1><?php echo $getProductData['product_name']?></h1>
<p><?php echo $getProductData['short_description']?></p>
<h4>R$<?php echo $getProductData['price']?></h4>
<div class="selectable">
<?php include('layouts/select.php');?>
</div>
</div>
<div class="row mt-3">
</div>
<?php
}
?><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script><script src="js/custom.js"></script> </div><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script><script src='https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js'></script></body></html>
the product page has an php include
<?php include('layouts/select.php');?>
I need to include the file layouts - colors and specific measures for each product:
layouts / id1.php
layouts / id2.php
layouts / id3.php
This is my layouts/selects file:
<? php
$id = echo $getProductData['id'];
if($id['acc']=='1') {
include('layouts/id1.php');}
if($id['acc']=='2') {
include('layouts/id2.php');}
if($id['acc']=='2') {
include('layouts/id3.php');}
?>
echo I get each product id
<?php echo $getProductData['id']?>
My problem ... I need to insert this id inside this include file.
<?php include('layouts/select.php');?>
or insert the id value in the specific php include, for example id = 1
<?php include('layouts/id1.php');?>
So I want to open the include file by selected id. Of course if there is another solution I accept it :)
<?php
include("layouts/id".$getProductData['id'].".php");
?>

CKFINDER in Ckeditor5 throws erorr

So I created a PHP on which I have added the CKEditor5 document That worked great,
After that I realised uploading images does not work. So I started digging in the documentation.
I realise I need a FileImageAdapter, instead of creating my own, I downloaded and uploaded CKfinder and the ckeditor5-ckfinder on GitHUb I uploaded both documents.
My test server is: https://webkeuken.be/
On that after login people can edit somethings, having a page like:
<?php
session_start();
if($_POST['promo'])
{
$xml=simplexml_load_file("../db.xml") or die("Error: Cannot create object");
$usernameDb = $xml->usernameDb;
$passwordDb = $xml->passwordDb;
$hostname = $xml->hostname;
$dbname = $xml->dbname;
// Create connection
$conn = new mysqli($hostname, $usernameDb, $passwordDb, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$_POST['promo']=str_replace("'", "'", $_POST['promo']);
//$sql = "INSERT INTO `product`( `naam`, `info`,`price`) VALUES (,,".."')";
$sql = "UPDATE `promo_balance` SET `promo`='".$_POST['promo']."' WHERE id=1";
if ($conn->query($sql) === TRUE) {
$_SESSION['input']= "New record created successfully";
$last = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
function verify()
{
if(!$_SESSION['user'])
{
if($_POST)
{
if($_POST['user']=="l-admin" && $_POST['pass']=="balance2016")
{
$_SESSION['user']="ok";
}
else
{
echo '
<form method="post" class="text-left" style="margin-top: 2%;">
<label style="margin-top: 2%;">USER</label>
<input type="text" name="user" class="form-control"/>
<label style="margin-top: 2%;">PASSWORD</label>
<input type="password" name="pass" class="form-control"/>
<input type="submit" class="form-control" style="margin-top: 2%;"/>
<span>Foute login gegevens</span>
</form>
';
}
}
else
{
echo '
<form method="post" class="text-left" style="margin-top: 2%;">
<label style="margin-top: 2%;">USER</label>
<input type="text" name="user" class="form-control"/>
<label style="margin-top: 2%;">PASSWORD</label>
<input type="password" name="pass" class="form-control"/>
<input type="submit" class="form-control" style="margin-top: 2%;"/>
</form>
';
}
}
}
function getPromo()
{
$xml=simplexml_load_file("../db.xml") or die("Error: Cannot create object");
$usernameDb = $xml->usernameDb;
$passwordDb = $xml->passwordDb;
$hostname = $xml->hostname;
$dbname = $xml->dbname;
$rij = array();
// Create connection
$conn = new mysqli($hostname, $usernameDb, $passwordDb, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT promo FROM promo_balance where id=1";
$item='';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$item = $row['promo'];
}
} else {
echo "0 results";
}
$conn->close();
return $item;
}
function toonForm(){
echo "<div class='col-lg-6'>";
echo "<h3><i class='fa fa-info'></i> Je kan hier een tekst schrijven, deze past zich aan.</h3>";
echo "<h3><i class='fa fa-bullhorn'></i> Ideaal voor je promoties.</h3>";
echo '<form method="post">';
echo '<label>Pas hier uw tekst aan</label>';
echo '
<div id="toolbar-container"></div>
<div id="editor">
'.getPromo().'
</div>
';
echo "<h5><i class='fa fa-pencil'></i> Deze tool werkt met Word Live</h5>";
echo '<input type="submit" class="btn btn-info btn-block" />';
echo '</form>';
}
function showOptions()
{
echo '<div class="row text-center">
<div class="col-lg-8 col-lg-offset-4">
<h2>Beheer uw promo vak</h2>
</div></div>';
echo '<div class="row">';
echo '<div class="col-lg-4">';
echo '
<script type="text/javascript">
google_ad_client = "ca-pub-3598185186227907";
google_ad_slot = "4603323478";
google_ad_width = 300;
google_ad_height = 250;
</script>
<!-- Extra -->
<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';
echo '</div>';
echo '<div class="col-lg-2 col-lg-offset-2 text-center ">';
echo '<div class="thumbnail">';
echo '<div class="caption">
<h1><i class="fa fa-arrow-left"></i></h1>
<h3>GA TERUG</h3>
<p> VORIG</p>
</div>';
echo '</div>';
echo '</div>';
echo '</div>';
//END OF ROW 1
echo '<div class="row">';
echo '<div class="col-lg-4">';
echo '<script type="text/javascript">
google_ad_client = "ca-pub-3598185186227907";
google_ad_slot = "4603323478";
google_ad_width = 300;
google_ad_height = 250;
</script>
<!-- Extra -->
<script type="text/javascript" src="//pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';
echo '</div>';
toonForm();
echo '</div>';
echo "</div>";
//END ROW 2
echo '<div class="row">';
echo '<div class="col-lg-4">';
echo '
<script type="text/javascript">
google_ad_client = "ca-pub-3598185186227907";
google_ad_slot = "4603323478";
google_ad_width = 300;
google_ad_height = 250;
</script>
<!-- Extra -->
<script type="text/javascript"
src="//pagead2.googlesyndication.com/pagead/show_ads.js">
</script>';
echo '</div>';
echo '</div>';// END ROW 3
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Krijtbord | Pas uw website aan in één klik.</title>
<meta name="description" content="Krijtbord | Pas uw website aan in één klik." />
<meta name="google-site-verification" content="ExQ89lGiGlXTIDoWcfx5CxMkRu-Wtubn8FYir2BJRU8" />
<link href="/bootstrap-assets/css/bootstrap.min.css" rel="stylesheet">
<!-- Style -->
<link href="/plugins/owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="/plugins/owl-carousel/owl.theme.css" rel="stylesheet">
<link href="/plugins/owl-carousel/owl.transitions.css" rel="stylesheet">
<link href="/plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet">
<link href="/plugins/Icons/et-line-font/style.css" rel="stylesheet">
<link href="/plugins/animate.css/animate.css" rel="stylesheet">
<link rel="stylesheet" href="/plugins/font-awesome-4.7.0/css/font-awesome.min.css">
<link href="/css/main.css" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid ruimte-top">
<div id="vliegerContent" style="padding-top: 4%; padding-bottom: 4%; border-bottom: 1px solid black;background: url('/tegels/bg.jpg'); background-size: cover;" class="text-center">
<h1 style=" width: 100%; text-shadow: 3px 3px #000; color: white; margin-top: 0; margin-left: auto; margin-right: auto; padding-top: 5%; padding-bottom: 5%;"class="text-vertical-center" data-stellar-background-ratio="0.5">Beheerders Pagina</h1>
</div>
<?php verify();?>
<div class="row" style="padding-bottom: 1%; background-color: white;">
</div>
<?php
if($_SESSION['user']=="ok")
{
showOptions();
}
?>
<div class="row" style="border-top: 1px solid black; margin-right: 0; margin-left: 0;">
<div class="text-center ruimte-top">
</div>
</div>
<div class="row ruimte-bottom" style=" margin-right: 0; margin-left: 0;">
<div class="col-lg-4 col-md-4 col-sm-4 col-lg-offset-2 col-md-offset-2 col-sm-offset-2">
<a rel="license" href="http://creativecommons.org/licenses/by-nc-nd/3.0/"><img
alt="Creative Commons License" style="border-width:0"
src="https://i.creativecommons.org/l/by-nc-nd/3.0/88x31.png"/></a><a rel="license"
href="http://creativecommons.org/licenses/by-nc-nd/3.0/"></a>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-lg-offset-2 col-md-offset-2 col-sm-offset-2">
<a rel="license" href="http://cogitatio.be" id="support">Met de steun van Cogitatio.be</a>
</div>
</div>
</div>
<!-- JS SCRIPTS -->
<script src="https://cdn.ckeditor.com/ckeditor5/15.0.0/decoupled-document/ckeditor.js"></script>
<script src="https://code.jquery.com/jquery-2.2.0.min.js" type="text/javascript"></script>
<script src="/js/modernizr.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="behaviour.js"></script>
<script>
$( "#verstuur" ).prop( "disabled", true );
$("#goed").hide();
function IsEmail()
{
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(regex.test(document.getElementById('email').value))
{
$( "#verstuur" ).prop( "disabled", false );
$("#goed").show();
$("#fout").hide();
}
else
{
$("#goed").hide();
$("#fout").show();
}
}
</script>
<script>
import CKFinder from '#ckeditor/ckeditor5-ckfinder/src/ckfinder';
DecoupledEditor
.create( document.querySelector( '#editor' ), {
plugins: [ CKFinder, ... ],
// Enable the "Insert image" button in the toolbar.
// toolbar: [ 'imageUpload', ... ],
ckfinder: {
// Upload the images to the server using the CKFinder QuickUpload command.
uploadUrl: '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json'
} )
.then( editor => {
const toolbarContainer = document.querySelector( '#toolbar-container' );
toolbarContainer.appendChild( editor.ui.view.toolbar.element );
} )
.catch( error => {
console.error( error );
} );
</script>
</body>
</html>
Now my page just renders the getPromo Content,
In my console I get:
Uncaught SyntaxError: Cannot use import statement outside a module
For those who need a CkFinder and CkEditor in there site.
The Setup is quite different as I thought. (Took me a lot of time).
CkEditor setup is quite easy. The CKFinder is ok. But on the docs they do an import. With:
import CKFinder from '#ckeditor/ckeditor5-ckfinder/src/ckfinder';
This caused an error.
Working Script for Upload
<script>
DecoupledEditor
.create( document.querySelector( '#editor' ), {
ckfinder: {
// Upload the images to the server using the CKFinder QuickUpload command.
uploadUrl: 'https://www.yumyumsushi.be/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images&responseType=json'
}
} )
.then( editor => {
const toolbarContainer = document.querySelector( '#toolbar-container' );
toolbarContainer.appendChild( editor.ui.view.toolbar.element );
} )
.catch( error => {
console.error( error );
} );
</script>

Display the results in the HTML

I am working on my code to fetch the data to output them in the HTML. I have got a problem with display the data in the html source outside of the PHP because I have received an error:
Warning: Invalid argument supplied for foreach() in /home/username/public_html/check_score.php on line 150
Here is the line 150:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
Here is the full code:
<?php
if(isset($_POST['btn1']))
{
sleep(1);
$ch = curl_init('http://example.com/check_score');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$message = "hey chris";
$header = "Delivered-To: example#gmail.com
Received: by 2002:a0c:938a:0:0:0:0:0 with SMTP id f10csp5715121qvf;
Sun, 2 Dec 2018 06:07:45 -0800 (PST)
the long list of the header goes here...
Hey rob,
How you doing?";
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('email' => $header, 'options'=>'long')));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
$score = json_decode($response);
?>
<script type="text/javascript">
$(document).ready(function() {
$('#myModal').modal('show');
});
</script>
<?php
}
?>
<form action="" method="post">
<div class="container">
<div class="form-group">
<button name="btn1" id="btn1" type="submit" class="btn btn-primary btn-block button-size">Check for score
</button>
</div>
</div>
</form>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height:600px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">SpamScore</h3>
</div>
<div class="modal-body" style="height: 77%;">
<?php
echo '<p><b>SpamScore points: <span id="bbb"></span>' . $score->score . '</b></p><hr>';
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
?>
</div><br>
<div class="modal-footer">
</div>
</div>
</div>
</div>
I have checked the results for the $score in the PHP which it show:
stdClass Object ( [success] => 1 [score] => 0.2 [rules] => Array ( [0] =>
stdClass Object ( [score] => 0.1 [description] => Message has a DKIM or DK
signature, not necessarily valid ) [1] => stdClass Object ( [score] => 0.1
[description] => DKIM or DK signature exists, but is not valid ) ) [report]
=> pts rule description ---- ---------------------- ------------------------
-------------------------- 0.1 DKIM_SIGNED Message has a DKIM or DK
signature, not necessarily valid 0.1 DKIM_INVALID DKIM or DK signature
exists, but is not valid )
When I have put the $score in the HTML, the results will show as empty.
It was working fine yesterday but today here it is not working. I dont really understand why the variable $score show as empty in the HTML when I can be able to fetch the data in PHP with no problem. I tried to find the answer on google but I can't find it anywhere.
Can you please help me with how I can be able to display the data in the HTML using the variable $score?
Thank you.
I just noticed something here. I'm not sure if it'll fix the error, but it may be a starting point. The first echoed line within your loop doesn't have a trailing semicolon:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
Give this a shot:
foreach($score->rules AS $rule) {
echo '<div name="test-row" style="margin-top:-1px">;
<div name="description" style="float: left; width:470px;">' . $rule->description . '</div>';
echo '<div name="scores" style="float: right">' . $rule->score . '</div>';
echo '</div><br><hr>';
}
Your $score variable fill on form submit, So you can't allow to $score variable after form post in the modal view.
Can you try following code instead of your codes,
UPDATED
My answer is changed for correct solution.
curl.php;
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_POST['submit'])
{
sleep(1);
$ch = curl_init('http://example.com/check_score');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$message = "hey chris";
$header = "Delivered-To: example#gmail.com
Received: by 2002:a0c:938a:0:0:0:0:0 with SMTP id f10csp5715121qvf;
Sun, 2 Dec 2018 06:07:45 -0800 (PST)
the long list of the header goes here...
Hey rob,
How you doing?";
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('email' => $header, 'options'=>'long')));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$response = curl_exec($ch);
} else {
$response = json_encode(array('success' => false));
}
echo $response;
exit;
?>
form.html;
<form action="" method="post">
<div class="container">
<div class="form-group">
<button name="btn1" id="btn1" type="submit" class="btn btn-primary btn-block button-size">Check for score
</button>
</div>
</div>
</form>
<script type="text/javascript">
$('form').on('submit', function(e){
e.preventDefault(0);
$.ajax({
url: 'curl.php',
data: {
submit: true
},
success: function(data) {
$('.modal-body').html('');
var data = JSON.parse(data);
console.log(data);
if(data.success){
$('#myModal').modal('show');
$('.modal-body').append('<p><b>SpamScore points: <span id="bbb"></span>' + data.score + '</b></p><hr>');
$.each(data.rules, function(key, value){
$('.modal-body').append('<div name="test-row" style="margin-top:-1px"><div name="description" style="float: left; width:470px;">' + value.description + '</div><div name="scores" style="float: right">' + value.score + '</div></div><br><hr>');
});
}
},
type: 'POST'
});
});
</script>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height:600px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">SpamScore</h3>
</div>
<div class="modal-body" style="height: 77%;"></div><br>
<div class="modal-footer"></div>
</div>
</div>
</div>
I do not able to test above codes, but it's must be work.

How to send push notifications to multiple devices using php script using FCM?

I'm new to push notifications using FCM from php to Android devices. From android side I have generated FCM reg_id & send it over php script & store into mysql database. Now, I would like to send notifications from php script to multiple android devices simultaneously.
Here is the php scripts that are used during sending push notifications :
1.firebase.php (reference link)
<?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 push message to multiple users by firebase registration ids
public function sendMultiple($registration_ids, $message) {
$fields = array(
'registration_ids' => $registration_ids,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// function makes curl request to firebase servers
private function sendPushNotification($fields) {
require_once('config.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);
// echo "Result".$result;
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
return $result;
}
}
?>
2.push.php : (reference link)
<?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']['timestamp'] = date('Y-m-d G:i:s');
return $res;
}
}
3.test.php
<?php
include_once('config.php');
require_once('DB_Functions.php');
require_once('firebase.php');
require_once('push.php');
$db = new DB_Functions();
$firebase = new Firebase();
$push = new Push();
if(isset($_POST['send']))
{
// $sendvalue = $_POST['send'];
ChromePhp::log('send it '.$_POST['send']." user
category:".$_POST['user_category']." Title : ".$_POST['message_title']." Message : ".$_POST['message_to_send']);
$ucategory = $_POST['user_category'];
ChromePhp::log('U category '.$ucategory);
// notification title
$messageTitle = isset($_POST['message_title']) ? $_POST['message_title'] : '';
// notification message
$messageToSend = isset($_POST['message_to_send']) ? $_POST['message_to_send'] : '';
ChromePhp::log('Message Title '.$messageTitle." Message:".$messageToSend);
$userslist_with_fcm_id = $db->getUsersFCMId($ucategory);
ChromePhp::log('FCM LIST '.$userslist_with_fcm_id->num_rows);
// var_dump($userslist_with_fcm_id);
$push->setTitle($messageTitle);
$push->setMessage($messageToSend);
$push->setIsBackground(FALSE);
$json = '';
$response = '';
if ($userslist_with_fcm_id->num_rows > 0) {
while ($row = mysqli_fetch_array($userslist_with_fcm_id)){
ChromePhp::log('FCM ID '.$row['fcm_id']);
$json = $push->getPush();
$regId = $row['fcm_id'];
$response = $firebase->send($regId, $json);
}
}
else{
echo '<h3>Oops ! You got empty data</h3>';
}
var_dump($response);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Admin Panel</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- jQuery UI -->
<link href="https://code.jquery.com/ui/1.10.3/themes/redmond/jquery-ui.css" rel="stylesheet" media="screen">
<!-- Bootstrap -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- styles -->
<link href="css/styles.css" rel="stylesheet">
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href="vendors/form-helpers/css/bootstrap-formhelpers.min.css" rel="stylesheet">
<link rel="stylesheet" href="css/pure-min.css">
<link href="css/forms.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<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>
<script type="text/javascript">
function sendMessage()
{
// alert("method called");
var chx = document.getElementsByTagName('input');
for (var i=0; i<chx.length; i++)
{
// If you have more than one radio group, also check the name attribute
// for the one you want as in && chx[i].name == 'choose'
// Return true from the function on first match of a checked item
if (chx[i].type == 'radio' && chx[i].checked)
{
// alert("checked: "+chx[i].value);
$.ajax({
url: 'test.php',
type: 'post',
data: {
send:"true",
user_category :chx[i].value,
message_title : document.getElementById('title').value,
message_to_send : document.getElementById('message').value
},
success: function(data, textStatus, jqXHR)
{
//data - response from server
// alert("success :".textStatus);
},
error: function (jqXHR, textStatus, errorThrown)
{
// alert("failed :".textStatus);
}
});
}
}
}
</script>
</head>
<body>
<div class="header">
<div class="container">
<div class="row">
<div class="col-md-5">
<!-- Logo -->
<div class="logo">
<h1>Admin Panel</h1>
</div>
</div>
<div class="col-md-5">
</div>
<div class="col-md-6">
<div class="navbar navbar-inverse" role="banner">
<nav class="collapse navbar-collapse bs-navbar-collapse navbar-right" role="navigation">
<ul class="nav navbar-nav">
<li class="dropdown">
My Account <b class="caret"></b>
<ul class="dropdown-menu animated fadeInUp">
<li>Update Profile</li>
<li>Logout</li>
</ul>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
<div class="page-content">
<div class="row">
<div class="col-md-2">
<div class="sidebar content-box" style="display: block;">
<ul class="nav">
<!-- Main menu -->
<li><i class="glyphicon glyphicon-tasks"></i>App Users</li>
<li><i class="glyphicon glyphicon-tasks"></i>Senate HALT Supporters</li>
<li><i class="glyphicon glyphicon-tasks"></i>Assembly HALT Supporters</li>
<li><i class="glyphicon glyphicon-tasks"></i>Call History</li>
<li><i class="glyphicon glyphicon-tasks"></i>Send Messages</li>
<!-- <li><i class=class="glyphicon glyphicon-tasks"></i>Voice Prompt</li> -->
</li>
</ul>
</div>
</div>
<div class="col-md-10">
<div class="row">
<div class="col-md-12">
<div class="content-box-large">
<div class="panel-body">
<form class="pure-form pure-form-stacked" method="POST">
<fieldset>
<legend>Create Message</legend>
<label for="title">Title</label>
<input type="text" value="Support Halt" id="title" name="title" class="pure-input-1-2" placeholder="Enter title">
<label for="message">Message</label>
<textarea class="pure-input-1-2" name="message" id="message" placeholder="Notification message!" rows="5" >Hello World</textarea>
<br>
<h5>
<input type="radio" id="user_category" name="user_category" value="userswithopponents"> Users with opponents<br>
<br>
<input type="radio" id="user_category" name="user_category" value="userswithsupporters"> Users with supporters<br>
<br>
<input type="radio" id="user_category" name="user_category" value="everyone"> Everyone <br>
<br>
<input type="radio" id="user_category" name="user_category" value="nyresidentsonly"> NY residents only </h5>
</br>
<input type="hidden" name="push_type" value="individual"/>
<button type="submit" class="btn btn-primary" onclick="sendMessage()">Send</button>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<link href="vendors/datatables/dataTables.bootstrap.css" rel="stylesheet" media="screen">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- jQuery UI -->
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="vendors/datatables/js/jquery.dataTables.min.js"></script>
<script src="vendors/datatables/dataTables.bootstrap.js"></script>
<script src="js/custom.js"></script>
<script src="js/tables.js"></script>
So, as of now I have tried to iterate over all reg_ids from database & call send method but it didn't send notifications to any devices .
Try to send device ID of multiple devices as an array. In your case,
$registration_ids must be an array of device IDs.
E.g
$registration_ids = array('Device ID 1', 'Device ID 2');
If you were to send notification via terminal the data part of the curl command would look like this:
{
"registration_ids": ["device_token_1", "device_token_2"],
"notification": {
"body": "Hello",
"title": "Hello",
"vibrate": 1,
"sound": 1
}
}
PHP code:
$body = array(
'registration_ids' => array("device_token_1", "device_token_2"),
'notification' => array('body' => 'Hello', 'title' => 'Hello', 'vibrate' => 1, 'sound' => 1)
);
Use 'registrations_ids' in place of 'to', if you want to send to the multiple users like:
$fields = array
(
'registration_ids' => $tokens,
'notification' => $msg
);
where $tokens = array("device token 1" , "device token 2");
if you want to send to the single user use 'to' , like
$fields = array
(
'to' => $token,
'notification' => $msg
);
where $token = "device token 1";
$notification_data = $this->common->get_all_record('table name',array()); //get all id from table
if($notification_data != NULL){
foreach ($notification_data as $notification_data_row) {
$registrationIds = $notification_data_row['token'];
#prep the bundle
$msg = array
(
'body' => 'body msg',
'title' => 'title',
'icon' => 'myicon',/*Default Icon*/
'sound' => 'mySound'/*Default sound*/
);
$fields = array
(
'to' => $registrationIds,
'notification' => $msg
);
$headers = array
(
'Authorization: key=' . "your key",
'Content-Type: application/json'
);
#Send Reponse To FireBase Server
$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec ( $ch );
// echo "<pre>";print_r($result);exit;
curl_close ( $ch );
}
}
To send firebase notifications to multiple users at once
add multiple firebase tokens to an array.
$token_ids = array('token1', 'token2');
Pass the tokens to the below shown function
Using below shown function you can also send images with your notification
if you don't want to send any image then just pass empty string
sendFirebaseNotification($token_ids ,"notification title", "message", "image_url");
I use this function
function sendFirebaseNotification($fb_key_array, $title, $message, $imageURL){
$authorization_key = "your_auth_key";
$finalPostArray = array('registration_ids' => $fb_key_array,
'notification' => array('body' => $message,
'title' => $title,
"image"=> $imageURL),
"data"=> array("click_action"=> "FLUTTER_NOTIFICATION_CLICK",
"sound"=> "default",
"status"=> "done"));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://fcm.googleapis.com/fcm/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($finalPostArray)); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: key='.$authorization_key));
$server_output = curl_exec ($ch);
curl_close ($ch);
//echo $server_output;
}
Below is the simple script to send notification. Try this.
<?php
$tokens = array('token_1','token_2','token_3');
$title = "Title Here";
$msg = "Subtitle or description Here";
//Custom Parameters if any
$customParam = array(
'redirection_id' => '2',
'redirection_type' => 'post_page' //'post_page','category_page','blog_page'
);
push_notification_android($tokens,$title,$msg,$customParam);
function push_notification_android($tokens,$title,$msg,$customParam) {
$url = 'https://fcm.googleapis.com/fcm/send';
$api_key = 'fcm_server_api_key';
$messageArray = array();
$messageArray["notification"] = array (
'title' => $title,
'message' => $msg,
'customParam' => $customParam,
);
$fields = array(
'registration_ids' => $tokens,
'data' => $messageArray,
);
$headers = array(
'Authorization: key=' . $api_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) {
echo 'Android: Curl failed: ' . curl_error($ch);
}
// Close connection
curl_close($ch);
return $result;
}
?>

Firebase Cloud Messaging using PHP

I'm trying to use PHP to send a notification from my localhost server. But I cannot get it to work. I previously received curl error. I solved it. But now it doesn't yield any errors. I can successfully send notifications from the Firebase console.
I have created FirebaseCloudMessaging.php to send the messages using curl.
<?php
/**
* Created by PhpStorm.
* User: Isuru
* Date: 18/11/2016
* Time: 16:47
*/
class FirebaseCloudMessaging {
// this methods send messages to a single device
public function send($to, $message){
$fields = array(
'to' => $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Send message to topic subscribers
public function sendToTopic($to, $message){
$fields = array(
'to' => '/topics/'. $to,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// Send push message to multiple devices
public function sendToMultipleDevices($registrationIds, $message){
$fields = array(
'to' => $registrationIds,
'data' => $message,
);
return $this->sendPushNotification($fields);
}
// CURL request to Firebase Platform
private function sendPushNotification($fields){
require_once __DIR__ . '/config.php';
// 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);
curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
// Disable SSL Certificate Support temporary
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));
}else{
json_decode($result);
}
// Close connection
curl_close($ch);
return $result;
}
}
And PushNotification.php is a model class for the messages.
<?php
/**
* Created by PhpStorm.
* User: Isuru
* Date: 17/11/2016
* Time: 01:32
*/
class PushNotification{
// push message title, message and image
private $title;
private $message;
private $image;
// data payload
private $data;
// flag indicating whether to
// show the push notification
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 setDataPayload($data){
$this->data = $data;
}
public function setIsBackground($is_background){
$this->is_background = $is_background;
}
public function getPushNotification(){
$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;
}
}
Following index.php shows the form and process the form submission.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase Cloud Messaging</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<style type="text/css">
/*Panel tabs*/
.panel-tabs {
position: relative;
bottom: 30px;
clear: both;
border-bottom: 1px solid transparent;
}
.panel-tabs > li {
float: left;
margin-bottom: -1px;
}
.panel-tabs > li > a {
margin-right: 2px;
margin-top: 4px;
line-height: .85;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
color: #ffffff;
}
.panel-tabs > li > a:hover {
border-color: transparent;
color: #ffffff;
background-color: transparent;
}
.panel-tabs > li.active > a,
.panel-tabs > li.active > a:hover,
.panel-tabs > li.active > a:focus {
color: #fff;
cursor: default;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border-radius: 2px;
background-color: rgba(255, 255, 255, .23);
border-bottom-color: transparent;
}
.input_width {
width: 520px;
}
</style>
</head>
<body>
<br>
<div class="container">
<?php
// Enabling error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
require_once __DIR__ . '/FirebaseCloudMessaging.php';
require_once __DIR__ . '/PushNotification.php';
$firebaseCloudMessaging = new FirebaseCloudMessaging();
$pushNotification = new PushNotification();
// optional payload
$payload = array();
// 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'] : '';
$pushNotification->setTitle($title);
$pushNotification->setMessage($message);
$pushNotification->setIsBackground(FALSE);
$pushNotification->setDataPayload($payload);
$json = '';
$response = '';
if ($push_type == 'topic') {
$json = $pushNotification->getPushNotification();
$response = $firebaseCloudMessaging->sendToTopic('news', $json);
} else if ($push_type == 'individual') {
$json = $pushNotification->getPushNotification();
$regId = isset($_GET['regId']) ? $_GET['regId'] : '';
$response = $firebaseCloudMessaging->send($regId, $json);
}
?>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="fl_window">
<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>
<div class="panel-heading">
<h3 class="panel-title">Firebase Cloud Messaging</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Single Device</li>
<li>Send To Topic 'News'</li>
</ul>
</span>
</div>
<div class="panel-body">
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="text"
placeholder="Enter Firebase Registration ID" id="redId" name="regId"
placeholder="Enter Firebase Registration ID">
</div>
</div>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="title"
placeholder="Enter Title" id="title" name="title">
</div>
</div>
<div class="form-group">
<div>
<textarea class="input_width input-lg" rows="5" name="message" id="message"
placeholder="Notification message!"></textarea>
</div>
</div>
<div class="form-group">
<div>
<input name="include_image" id="include_image" type="checkbox"> Include
image
</div>
</div>
</fieldset>
<input type="hidden" name="push_type" value="individual"/>
<div class=" text-center">
<input type="submit" class="btn btn-primary" value="SUBMIT"/>
</div>
</form>
</div>
<div class="tab-pane" id="tab2">
<form class="pure-form pure-form-stacked" method="get">
<fieldset>
<div class="form-group">
<div class="input_width">
<input
class="form-control input-lg" type="text"
placeholder="Enter Title" id="title1" name="title"
placeholder="Enter Title">
</div>
</div>
<div class="form-group">
<div>
<textarea class="input_width input-lg" rows="5" name="message" id="message"
placeholder="Notification message!"></textarea>
</div>
</div>
<div class="form-group">
<div>
<input name="include_image" id="include_image" type="checkbox"> Include
image
</div>
</div>
</fieldset>
<input type="hidden" name="push_type" value="topic"/>
<div class=" text-center">
<input type="submit" class="btn btn-primary" value="Send to Topic Subscribers"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</html>
And config.php stores the web API. Is there a way to debug the code? For example to check whether Google accepts my request? Any suggestion is appreciated.
Thank you!
Change your $fields array like this
$fields = array (
'registration_ids' => array (
$registrationIds
),
'notification' => array (
"title" => "Title here",
"text" => $message
));
It's work for me

Categories