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
Related
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>
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.
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;
}
?>
The question may seems vague and I apologise fully, so I'll try and explain it better here. Basically, I have 2 .php files, the index.php and php.php. On index.php a user will enter their username into the form where they would then submit the input, php.php then grabs the username (using the $_POST[] method.) and display the data on that page. The URL at this point looks like this;
http://minecraftnamespy.esy.es/php.php.
How would I do it so that the username the user types would be added onto the URL? E.g;
User inputs: _scrunch as username.
URL now changes from http://minecraftnamespy.esy.es/php.php to
http://minecraftnamespy.esy.es/php?=_scrunch
I should like to point out that I am working with the Mojang API here.
My php.php code is:
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (
$username = $_POST["username"]
) {
//do nothing
} else {
$username = "notch";
}
//allow the user to change the skin
$skinChange = "<a href='https://minecraft.net/profile/skin/remote?url=http://skins.minecraft.net/MinecraftSkins/$username.png' target='_blank' </a>";
//grabbing the users information
if ($content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username))
) {
$userSkin = "<img src='https://mcapi.ca/skin/3d/$username' />";
} else {
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username) . '?at=0');
if( $http_response_header['0'] == "HTTP/1.1 204 No Content") {
echo "Not a valid Minecraft Username! <a href='index.php'><button>Search Again?</button></a>";
die;
}
$json = json_decode($content);
foreach ($json as $currentName) {
$currentName = $currentName;
}
$userSkin = "<img src='https://mcapi.ca/skin/3d/$currentName' />";
}
// Decode it
$json = json_decode($content);
// Check for error
if (!empty($json->error)) {
die('An error happened: ' . $json->errorMessage);
}
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
$time = date('Y-m-d H:i:s', $name->changedToAt);
$input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
//url to users 2D head (avatar)
$usersAvatar = "https://mcapi.ca/avatar/2d/$input/55";
//user's Avatar as favivon
$usersFavicon = "<link rel='shortcut icon' href='$usersAvatar' type='image/png' />";
//use $uuid tp grab UUID of the user - ---- - - - use $names to get name history of the user.
?>
<html>
<head>
<?php echo $usersFavicon;?>
<title><?php echo $username?>'s Information</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Find a player skin!</title>
<style>
body {
background-image: url(http://minecraftnamespy.esy.es/grad.jpg);
background-position: bottom;
background-repeat: no-repeat;
background-size: 100% 500px;
}
#content {
margin-left: auto;
margin-right: auto;
width: 60%;
}
img.logo {
margin-right: auto;
margin-left: auto;
display: block;
padding: 30px;
max-width: 100%;
height: auto;
width: auto\9;
}
.center {
margin-left: auto;
margin-right: auto;
}
.footer {
text-align: center;
}
p.responsive {
word-wrap: break-word;
}
</style>
</head>
<body>
<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://minecraftnamespy.esy.es/source.png" alt="View Source on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png">
<!--debug -->
<?php ?>
<div id="content">
<div class="col-md-12">
<img class="logo" src="http://minecraftnamespy.esy.es/logo.png">
</div>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s UUID</h3>
</div>
<div class="panel-body">
<p class="responsive"><?php echo $uuid;?></p>
</div>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Name History (Oldest to Most Recent)</h3>
</div>
<div class="panel-body">
<?php echo implode(', <br>', $names) ;?>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Avatar</h3>
</div>
<div class="panel-body">
<div class="center">
<?php echo $userSkin;?>
</div>
<p><?php echo $skinChange;?>Change this skin to yours!</a></p>
</div>
</div>
</div>
<div class="col-md-12">
<div class="btn-group pull-right" role="group" aria-label="">
<button type="button" class="btn btn-default">Search another Username?</button>
</div>
</div>
<div class="footer">
<span>Created by _scrunch</span> •
<span>©2015</span> •
<span>Find me on PMC</span>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="Y8MWQB9FCUTFJ">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
</body>
</html>
Here's the form that is used to submit the username on index.php.
<form action="php.php" method="GET">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter username">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
You want a GET request, which are visible in the URL in the form of http://example.com/index.php?username=_scrunch
A POST request is invisible (i.e, it does not appear in the URL) and are commonly used to send sensitive data (though a POST is not enough for data security!).
Converting your POST into a GET is a simple matter of changing from
$username = $_POST["username"]
to
$username = $_GET["username"]
You can use this, note the additional inclusion of
if (!$_GET["username"]) {
exit;
}
which causes your page to exit loading and protects against misuse of the page if username is not present.
<?php
//error_reporting(E_ALL & ~E_NOTICE);
// Load the username from somewhere
if (!$_GET["username"]) {
exit;
}
if (
$username = $_GET["username"]
) {
//do nothing
} else {
$username = "notch";
}
//allow the user to change the skin
$skinChange = "<a href='https://minecraft.net/profile/skin/remote?url=http://skins.minecraft.net/MinecraftSkins/$username.png' target='_blank' </a>";
//grabbing the users information
if ($content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username))
) {
$userSkin = "<img src='https://mcapi.ca/skin/3d/$username' />";
} else {
$content = file_get_contents('https://api.mojang.com/users/profiles/minecraft/' . urlencode($username) . '?at=0');
if( $http_response_header['0'] == "HTTP/1.1 204 No Content") {
echo "Not a valid Minecraft Username! <a href='index.php'><button>Search Again?</button></a>";
die;
}
$json = json_decode($content);
foreach ($json as $currentName) {
$currentName = $currentName;
}
$userSkin = "<img src='https://mcapi.ca/skin/3d/$currentName' />";
}
// Decode it
$json = json_decode($content);
// Check for error
if (!empty($json->error)) {
die('An error happened: ' . $json->errorMessage);
}
// Save the uuid
$uuid = $json->id;
// Get the history (using $json->uuid)
$content = file_get_contents('https://api.mojang.com/user/profiles/' . urlencode($uuid) . '/names');
// Decode it
$json = json_decode($content);
$names = array(); // Create a new array
foreach ($json as $name) {
$input = $name->name;
if (!empty($name->changedToAt)) {
// Convert to YYYY-MM-DD HH:MM:SS format
$time = date('Y-m-d H:i:s', $name->changedToAt);
$input .= ' (changed at ' . $time . ')';
}
$names[] = $input; // Add each "name" value to our array "names"
}
//url to users 2D head (avatar)
$usersAvatar = "https://mcapi.ca/avatar/2d/$input/55";
//user's Avatar as favivon
$usersFavicon = "<link rel='shortcut icon' href='$usersAvatar' type='image/png' />";
//use $uuid tp grab UUID of the user - ---- - - - use $names to get name history of the user.
?>
<html>
<head>
<?php echo $usersFavicon;?>
<title><?php echo $username?>'s Information</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<title>Find a player skin!</title>
<style>
body {
background-image: url(http://minecraftnamespy.esy.es/grad.jpg);
background-position: bottom;
background-repeat: no-repeat;
background-size: 100% 500px;
}
#content {
margin-left: auto;
margin-right: auto;
width: 60%;
}
img.logo {
margin-right: auto;
margin-left: auto;
display: block;
padding: 30px;
max-width: 100%;
height: auto;
width: auto\9;
}
.center {
margin-left: auto;
margin-right: auto;
}
.footer {
text-align: center;
}
p.responsive {
word-wrap: break-word;
}
</style>
</head>
<body>
<img style="position: absolute; top: 0; right: 0; border: 0;" src="http://minecraftnamespy.esy.es/source.png" alt="View Source on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_orange_ff7600.png">
<!--debug -->
<?php ?>
<div id="content">
<div class="col-md-12">
<img class="logo" src="http://minecraftnamespy.esy.es/logo.png">
</div>
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s UUID</h3>
</div>
<div class="panel-body">
<p class="responsive"><?php echo $uuid;?></p>
</div>
</div>
</div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Name History (Oldest to Most Recent)</h3>
</div>
<div class="panel-body">
<?php echo implode(', <br>', $names) ;?>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><?php echo $username;?>'s Avatar</h3>
</div>
<div class="panel-body">
<div class="center">
<?php echo $userSkin;?>
</div>
<p><?php echo $skinChange;?>Change this skin to yours!</a></p>
</div>
</div>
</div>
<div class="col-md-12">
<div class="btn-group pull-right" role="group" aria-label="">
<button type="button" class="btn btn-default">Search another Username?</button>
</div>
</div>
<div class="footer">
<span>Created by _scrunch</span> •
<span>©2015</span> •
<span>Find me on PMC</span>
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="Y8MWQB9FCUTFJ">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal – The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
</body>
</html>
I have encountering a problem..
It outputted an error : Cannot modify header information..
What would be the cause? And how could i fix it..
Thanks for the help.. I've check all, but then still I cannot fix it. What would be the problem?
Here is my code below:
<!DOCTYPE html>
<html dir="ltr" lang="en-US"><head><!-- Created by Artisteer v4.3.0.60747 -->
<meta charset="utf-8">
<title>Home</title>
<meta name="viewport" content="initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width">
<link rel="stylesheet" href="style.css" media="screen">
<link rel="stylesheet" href="style.responsive.css" media="all">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Salsa|PT+Sans&subset=latin">
<script src="jquery.js"></script>
<script src="script.js"></script>
<script src="script.responsive.js"></script>
<script>jQuery(function ($) {
'use strict';
if ($.fn.themeSlider) {
$(".art-slidecontainera65d557e889141cb8638b82feda1c335").each(function () {
var slideContainer = $(this), tmp;
var inner = $(".art-slider-inner", slideContainer);
inner.children().filter("script").remove();
var helper = null;
if ($.support.themeTransition) {
helper = new BackgroundHelper();
helper.init("fade", "next", $(".art-slide-item", inner).first().css($.support.themeTransition.prefix + "transition-duration"));
inner.children().each(function () {
helper.processSlide($(this));
});
} else if (browser.ie && browser.version <= 8) {
var slidesInfo = {
".art-slidea65d557e889141cb8638b82feda1c3350": {
"bgimage" : "url('images/slidea65d557e889141cb8638b82feda1c3350.jpg')",
"bgposition": "0 0",
"images": "",
"positions": ""
},
".art-slidea65d557e889141cb8638b82feda1c3351": {
"bgimage" : "url('images/slidea65d557e889141cb8638b82feda1c3351.jpg')",
"bgposition": "0 0",
"images": "",
"positions": ""
}
};
$.each(slidesInfo, function(selector, info) {
processElementMultiplyBg(slideContainer.find(selector), info);
});
}
inner.children().eq(0).addClass("active");
slideContainer.themeSlider({
pause: 2600,
speed: 600,
repeat: true,
animation: "fade",
direction: "next",
navigator: slideContainer.siblings(".art-slidenavigatora65d557e889141cb8638b82feda1c335"),
helper: helper
});
});
}
});
</script></head>
<body>
<div id="art-main">
<header class="art-header">
<div class="art-shapes">
</div>
<h1 class="art-headline">
FPES
</h1>
<h2 class="art-slogan">Faculty Performance Evaluation System.</h2>
<?php
//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("db_fpes",$connect); //select the table
if(isset($_POST['btn_submit'])){
$username = $_POST['username'];
$password = $_POST['pass'];
$result = mysql_query ("SELECT * FROM professors where fac_stat = 1 and Faculty_code = '".$username."' and Faculty_code = '".$password."' ");
if($username == 'admin' && $password == 'admin' && mysql_num_rows($result) == 0 ){
header('Location: admin/home.php'); die;
}
else
{
$row = mysql_fetch_assoc($result);
if($row['system_user'] == 1){
header('Location: Grading/index.php'); die;
}
else if($row['system_user'] == 2){
header('Location: Secretary/home.php'); die;
}
else
header('Location: index.php'); die;
}
}
?>
<nav class="art-nav">
<ul class="art-hmenu"><li>Home</li>
<li>About Us</li>
</ul>
</nav>
</header>
<div class="art-sheet clearfix">
<div class="art-layout-wrapper">
<div class="art-content-layout">
<div class="art-content-layout-row">
<div class="art-layout-cell art-content"><article class="art-post art-article">
<div class="art-postcontent art-postcontent-0 clearfix"><div class="art-content-layout-wrapper layout-item-0">
<div class="art-content-layout layout-item-1">
<div class="art-content-layout-row">
<div class="art-layout-cell layout-item-2" style="width: 100%" >
<p></p><div id="a65d557e889141cb8638b82feda1c335" style="position: relative; display: inline-block; z-index: 0; margin: 0px; border-width: 0px; " class="art-collage">
<div class="art-slider art-slidecontainera65d557e889141cb8638b82feda1c335" data-width="900" data-height="287">
<div class="art-slider-inner">
<div class="art-slide-item art-slidea65d557e889141cb8638b82feda1c3350" >
</div>
<div class="art-slide-item art-slidea65d557e889141cb8638b82feda1c3351" >
</div>
</div>
</div>
<div class="art-slidenavigator art-slidenavigatora65d557e889141cb8638b82feda1c335" data-left="1" data-top="1">
</div>
</div>
<p>
</p><p>
</p>
</div>
</div>
</div>
</div>
<div class="art-content-layout layout-item-1">
<div class="art-content-layout-row">
<div class="art-layout-cell layout-item-3" style="width: 67%" >
<h2><span style="color: rgb(128, 0, 0); line-height: 51px; font-size: 40px;">Welcome </span><span style="color: rgb(108, 127, 147); line-height: 31px; font-size: 28px;">to our site!</span></h2>
<h3><img width="250" height="195" alt="" src="images/1037312_small500.jpg" style="float: left; margin-right: 15px;" class="">Performance Faculty Evalutaion System. </h3>
<p>Insert Description Here!.<br></p>
</div>
<div class="art-layout-cell layout-item-4" style="width: 33%" >
<form method = "post" action = "">
<h1>Please Login<br></h1><p style="margin-top: 10px;"> Username: <input type="text" name = "username" > </p><p>
<p> Password: <input type="text" name = "pass"></p><p style="text-align: right;">
<input type = "submit" name = "btn_submit" class="art-button" value = "Login"/><br></p>
</form>
</div>
</div>
</div>
</article></div>
</div>
</div>
</div>
</div>
<footer class="art-footer">
<div class="art-footer-inner">
<p>GoMiracles © 2014 - 2015. All Rights Reserved.<br></p>
</div>
</footer>
</div>
</body></html>
Headers already sent is an issue where you try to redirect an user with header() or when you try to start a session session_start() when the browser already rendered content (for example html, but can also be a PHP echo statement for example).
To fix the issue, check if you have any echo() statements or raw HTML before sending headers, and check if you do not have whitespaces in front of <?php.
A more detailed answer to help you fix this issue can be found here: https://stackoverflow.com/a/8028987/4274852
I suspect you did not provide us with all your code, as I cannot find any specific problems in yours at the moment. I hope the link above helps you to debug your code, if not: Make sure to post everything above your PHP code.
Just a note: I see you are still using mysql_query statements, which are deprecated. Use msqli or PDO instead.
Edit
I see you posted your code, try replacing all your PHP code at the top of your page instead of in the middle and it should work. In your current code, you have raw HTML before the PHP code (<h1> and <p> elements in this case), which makes it impossible to send more header data using header(), as all headers were already sent before rendering the page.
I editted your code to fix the issue hopefully, you can find it here (instead of posting it here, which would make an awkward long answer):
http://pastebin.com/0JfBdjU5