Getting information from Pusher channel using PHP - php

I'm getting new to "Pusher" (the websocket api) and I'm having hard time to understand how can I fetch information from the server after sending it to the channel.
For example, this is my code:
<?php
include "pusher/Pusher.php";
?>
<script src="http://js.pusher.com/2.1/pusher.min.js"></script>
<script type="text/javascript">
var pusher = new Pusher('c77c12b92e38f4156e9c');
var channel = pusher.subscribe('test-channel');
channel.bind('my-event', function(data) {
alert('An event was triggered with message: ' + data.message);
});
</script>
<?php
$pusher = new Pusher($config["pusher_key"], $config["pusher_secret"], $config["pusher_id"]);
$pusher->trigger(channel, 'my-event', array('message' => 'Test Message') );
Now, my information is sent to the server, but I don't know how to get it.
Thanks.

You can find the source for a very simple example here:
https://github.com/leggetter/pusher-examples/tree/master/php/hello-world/src
And this example working here:
http://www.leggetter.co.uk/pusher/pusher-examples/php/hello-world/src/
The problem you are seeing is that you are triggering the event on the server before the page has rendered in the browser. So, a connection has not been made by the browser to Pusher, nor has a subscription been made.

You can try something liked this,for php pusher library I used composer
<div class="notification">
</div>
<script>
var pusher = new Pusher('APP_KEY');
var notificationsChannel = pusher.subscribe('notification');
notificationsChannel.bind('new_notification', function(notification){
var message = notification.message;
toastr.success(message);
});
var sendNotification = function(){
var text = $('input.create-notification').val();
$.post('./notification/index.php', {message: text}).success(function(){
console.log('Notification sent!');
});
};
$('button.submit-notification').on('click', sendNotification);
</script>
HTML
<input class="create-notification" placeholder="Send a notification :)"/>
<button class="submit-notification">Go!</button>
Using PHP in this case
require(dirname(__FILE__).'/../vendor/autoload.php');
$app_id = 'APP_ID';
$app_key = 'APP_KEY';
$app_secret = 'APP_SECRET';
$pusher = new Pusher($app_key, $app_secret, $app_id,array( 'encrypted' => true ));
$data['message'] = $_POST['message'];
$pusher->trigger('notification', 'new_notification', $data);
For more follow this link
Recommended folder structure -
You can add following for more UX kind'a look -
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<script src="http://js.pusher.com/2.2/pusher.min.js" type="text/javascript"></script>

Related

Websockets : Send message from php server to clients

I'm trying to send messages from my file index.php (server) to clients connected using websockets.
My javascript file to create the client connection :
var websocket_server = new WebSocket("ws://localhost:4950/");
websocket_server.onopen = function(e) {
console.log("connected");
}
websocket_server.onmessage = function(e)
{
console.log('message received from server');
}
index.php:
$msg = "Message from server";
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR,1) or die("prbl options\n");
socket_connect($sock, '127.0.0.1', 4950) or die("could not connect\n");
socket_write($sock, $msg, strlen($msg));
The client connect to the websocket is successful, but when I run the PHP file, I get nothing (no error and no message in the console).
In other words, javascript doesn't consider my socket_write as a message :/
Any ideas? :)
I have found a solution thanks to #ADyson ;)
I'm using SSE server sent events now and it works !But I'd like to know if my code is 'proper' or if there is a more 'adequate' way.
I'm using session superglobals to pass server informations changes to another file which is constantly reading it as event-stream (that's the way SSE works).
index.php :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js">
</script>
<script type="text/javascript" src="stream.js">
</script>
</head>
<body>
<a>Receive message</a>
</body>
</html>
stream.js (listening to the server) :
var serv = new EventSource("server.php");
serv.onmessage = function(e) {
var jdata = JSON.parse(e.data);
console.log(jdata.message);
};
serv.onopen = function(e) {
console.log('Connection opened');
}
$(document).ready(function(){
$('a').click(function(){
receive_msg();
});
});
function receive_msg(){
$.ajax({
type: "POST",
url: 'controller.php',
data: {action: 'send'}
});
}
controller.php :
<?php
session_start();
if (isset($_POST['action'])) {
$_SESSION['server']="you have received a message";
}
server.php :
<?php
session_start();
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
if (isset($_SESSION['server'])) {
$data = array(
'message'=> $_SESSION['server']
);
$data = json_encode($data);
echo "data: {$data}\n\n";
unset($_SESSION['server']);
}
The way it works :
Clients connect to the server.php and read the file constantly. When the server wants to send a message to clients, it creates a session variable. Server.php reads the variable and pass it to my js file. Then the variable is destroyed so we pass the message only once.

auto refresh the div with dynamic data

I have a div section. I want to reload this section every 5 seconds. How do I do this. Here is my code:
<script>
$("#send_parent_general_chat").submit(function()
{
var rec = $("#data").val();
var msg = $("#msg").val();
var dataString = 'rec='+ rec + '&msg='+ msg;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Client/send_general_parent_chat_msg/<?php echo $per_job->id;?>",
data: dataString,
cache: false,
success: function(result){
$('#display_general_msg').html(result);
$('#send_parent_general_chat')[0].reset(); //form reset
}
});
return false;
});
</script>
<script>
$(document).ready(function(){
setInterval(function(){
// alert("===111==");
$("#display_general_msg").load('<?php echo base_url(); ?>" + "Client/refresh_general_parent_chat_msg/<?php echo $per_job->id;?>')
}, 5000);
});
</script>
I have created one more controller for refreshing the div I have used the time interval function but it is not loading, it shows this error:
Access forbidden!
You don't have permission to access the requested object. It is either read-protected or not readable by the server.
If you think this is a server error, please contact the webmaster.
Error 403
I need to refresh only the div content not the whole page.
How do I achieve this?
You can Use :
setTimeout(function()
{
Your_Function(); //this will send request again and again;
}, 5000);
Replace Your_Function with your Function Name.
Hope this will help !!
Below is an example which will update the contents in every 5 seconds using php websockets. This is a simple example, but you can use it to modify to fit for your application needs. You don't need the timeout functions on the client side here we use server sleep
Install the Workerman socket library
composer require workerman/workerman
The client side code
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
//alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:2346");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
//alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
//alert("Message is received..." + received_msg);
document.getElementById("demo").innerHTML = "Timestamp is updated every 5 sec " +received_msg;
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
Run WebSocket
</div>
<div id="demo" style="font-size: 64px; color: red;"></div>
</body>
</html>
The Server side code
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Workerman\Worker;
// Create a Websocket server
$ws_worker = new Worker("websocket://0.0.0.0:2346");
// 4 processes
$ws_worker->count = 4;
// Emitted when new connection come
$ws_worker->onConnect = function($connection)
{
echo "New connection\n";
};
// Emitted when data received
$ws_worker->onMessage = function($connection, $data)
{
// Send hello $data
while(true) {
$connection->send(time());
sleep(5); //Sleep for 5 seconds to send another message.
}
};
// Emitted when connection closed
$ws_worker->onClose = function($connection)
{
echo "Connection closed\n";
};
// Run worker
Worker::runAll();
The backend service can be started with the following command from the terminal or you can autostart on boot if you want.
$php index.php start
Here index.php is our backendnd file name.
Just start the service and load the page then you can see the timestamp is updated every 5 seconds which comes from the server side. This is a working example tested on my local machine. Try and let me know if you need any other help.
The output
you can also try below one:
setInterval(function(){
loadlink() // this will run after every 5 seconds
}, 5000);
setInterval approach will be more accurate than the setTimeout approach
// or
$(function(){ // document.ready function...
setTimeout(function(){
$('form').submit();
},5000);
});

Trying to use php site with socket.io chat application but it downloads php code instead

I have created a chat application using the walk through on socket.io
I have added further content to the application, including database info, which meant I had to change the index.html to current session.php.
Now when I try and run the application, it just downloads a document with all the code for the page, and it does not run.
I have changed all the code to current session.php where necessary.
If I change the file name back to current session.html and change the relevant code, it then works fine....
I really need to have database info on the page, which is why it needs to be current session.php
Does anyone know why it does this? Is there a work around?
Code for index.js:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/currentsession', function(req, res){
res.sendFile(__dirname + '/Staff/html/current session.php');
});
app.get('/question', function(req, res){
res.sendFile(__dirname + '/Student/Question.php');
});
io.emit('some event', { for: 'everyone' });
io.on('connection', function(socket){
socket.broadcast.emit('hi');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.join('/currentsession');
});
var nsp = io.of('/question');
nsp.on('connection', function(socket){
socket.join('/question');
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
var nsp = io.of('/currentsession');
nsp.on('connection', function(socket){
socket.on('go-to-page', function(data){
io.of('/question').emit('go-to-page', { href: "//selene.hud.ac.uk/u1555602"});
});
});
http.listen(4000, function(){
console.log('listening on *:4000');
});
code for current session.php
<?php include('server.php') ?>
<?php
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: sign in.php');
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Wireless Response System</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="../css/style.css" rel="stylesheet" type="text/css">
</head>
<div class="heading">
<div class="php">
<?php
if (isset($_SESSION['username'])) :
$query = ("SELECT discipline FROM user WHERE username = '".$_SESSION['username']."'");
$resultset = $conn->query($query);
while ($user = $resultset->fetch()) {
echo '<h1> Discipline:'; echo $user["discipline"]; '</h1>'; }
endif
?>
</div>
<nav>
<ul>
<form action="">
<button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io('/currentsession');
$('form').submit(function(){
socket.emit('go-to-page', $('#m').val());
$('#m').val('');
return false;
});
socket.on('go-to-page', function (data) {
window.location.replace(data.href);
});
});
</script>
res.sendFile(__dirname + '/Staff/html/current session.php');
You have written an HTTP server using Node.js.
For some HTTP requests, your server will respond by reading the source code of a PHP file and then sending it to the browser.
You need to run the PHP program and send its output, not the source code.
Typically you would do this by using a server optimised for running PHP (such as Apache HTTPD) and having the browser make the request to that server and not the one created using Node.js.

using twilio php library in mobile devices (ios and android)?

I'm working on a simple application using twlio php library to make out going calls.
everything seems to be working as it should in web browser. However, when i test the simple php page in a mobile device (iphone for example), nothing works! I get the page loaded but I cannot make any outgoing calls!
this is my code:
<?php
include 'Services/Twilio/Capability.php';
// put your Twilio API credentials here
$accountSid = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// put your Twilio Application Sid here
$appSid = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('jenny');
$token = $capability->generateToken();
?>
<!DOCTYPE html>
<html>
<head>
<title>Hello Client Monkey 4</title>
<script type="text/javascript"
src="//static.twilio.com/libs/twiliojs/1.2/twilio.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
Twilio.Device.setup("<?php echo $token; ?>");
Twilio.Device.ready(function (device) {
$("#log").text("Ready");
});
Twilio.Device.error(function (error) {
$("#log").text("Error: " + error.message);
});
Twilio.Device.connect(function (conn) {
$("#log").text("Successfully established call");
});
Twilio.Device.disconnect(function (conn) {
$("#log").text("Call ended");
});
Twilio.Device.incoming(function (conn) {
$("#log").text("Incoming connection from " + conn.parameters.From);
// accept the incoming connection and start two-way audio
conn.accept();
});
function call() {
// get the phone number to connect the call to
params = {"PhoneNumber": $("#number").val()};
Twilio.Device.connect(params);
}
function hangup() {
Twilio.Device.disconnectAll();
}
</script>
</head>
<body>
<button class="call" onclick="call();">
Call
</button>
<button class="hangup" onclick="hangup();">
Hangup
</button>
<input type="text" id="number" name="number"
value="Phone Number/>
<div id="log">Loading pigeons...</div>
</body>
</html>
Could someone please advise on this issue? am I missing something?
Twilio developer evangelist here.
Sadly iOS does not currently support either WebRTC or Flash, both of the technologies that Twilio Client uses to make phone calls from your web browser. So, Twilio Client JavaScript will not work on an iPhone. Recent versions of Chrome on Android do support WebRTC, so you should be able to use Twilio Client on those devices.

Using variables with jQuery and embedded objects

I am using a java script library that allows me to query information from a shoutcast server such as the current song playing, recent songs played, and etc which all works fine. This library places the data into a span element on the page based on it's defined ID.
Now, my issue is that I am trying to pass the contents of my span which is a string (current song title) to PHP so that I can use it for my Twitter library which uses PHP to post to Twitter.
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
$twitter->send('testing...'); // This will send testing to twitter status!
?>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
$.ajax({
url: 'receiver.php',
type: 'POST',
data: { data : nowplaying },
success: function (result) {
console.log(nowplaying);
}
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
This SPAN has the current song title within it upon page load which is good. I want to pass this data to my PHP above to post to twitter.
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Any assistance with this will be very helpful.. I have looked at so many places with no luck and this is getting very frustrating.
Regards,
I have posted my updated code which successfully sends a jQuery variable to PHP using AJAX upon a page load.
Here is the HTML/JAVASCRIPT
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="jquery.shoutcast.min.js"></script>
<!-- Current Song Played -->
<script>
// Get current song playing and load it into an element with an ID of songtitle
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000,
interval : 5000,
}).stats(function(){
$('#songtitle').text(this.get('songtitle'));
$(document).ready(function() {
console.log("Document Ready!");
var content = $('#songtitle').text();
var nowplaying = ("#NowPlaying: " + content);
console.log('TOP' + nowplaying);
$.post("receiver.php", //Required URL of the page on server
{ // Data Sending With Request To Server
name:nowplaying,
},
function(response){ // Required Callback Function
alert("Response: " + response); // "response" receives - whatever written in echo of above PHP script.
});
});
});
</script>
<!-- Last 10 Songs Played -->
<script>
// Get last 10 songs playing and load it into an ul element
$.SHOUTcast({
host : 'live.soundcheck.xyz',
port : 8000
}).played(function(tracks){
$('ul').html('');
$.each(tracks,function(k,track){
$('ul').append('<li>'+track.title+'</li>');
});
});
</script>
</head>
<body>
<span id="songtitle" name="songtitle"></span>
<ul></ul>
</body>
</html>
Here is the PHP code
<?php
// Insert your keys/tokens
$consumerKey = '';
$consumerSecret = '';
$accessToken = '';
$accessTokenSecret = '';
// Full path to twitterOAuth.php (change OAuth to your own path)
require_once('/home/soundcheck/public_html/app/twitter/auto/twitteroauth.php');
require_once('/home/soundcheck/public_html/app/twitter/auto/twitter.class');
// create new instance
$twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);
if($_POST["name"])
{
$name = $_POST["name"];
// Here, you can also perform some database query operations with above values.
// echo "Welcome ". $name ."!"; // Success Message
echo $name; // Success Message
$tag = ('# http://soundcheck.xyz #radio - powered by: http://buzzzhost.com');
$twitter->send($name .= $tag); // This will send testing to twitter status!
}
?>
I hope this will help someone out there as I was searching for a long time for a good option.

Categories