How do push notifications work? - php

I'm trying to implement push notifications on my PHP-based website. The goal is to make something similiar to what Stackoverflow and other sites have which notify a user in real-time when they get messages.
I'm using mysql as my database, Apache as my server, and am considering using Amazon-SNS as the framework for these notifications since that is what that service seems to be intended for.
I'm having a hard understanding from the literature how programmatically the sending.php and receiving.php pages are set up. I'd assume the sending.php page just involves a $_POST['message'] to some page, but from there I'm really lost.
If something could help me understand what the receiving.php page would look like for a push notification I would greatly appreciate it.

Working
HTML5rocks have provided a good explanation here, about how websockets work.
Well you can make use of Websockets for the browsers that support it (since all modern browsers provide good support)
Getting Started
You can get started with these few resources :
HTML5rocks
Nettuts+
Nettuts+ provide a good tutorial for getting started with websockets.
For Browsers Supporting Websockets
Fallback
You can use Modernizr to detect whether the Client's browser has support for websockets or not & as a fallback you can make use of flash instead of Websockets.
For those projects, when running on browsers with no WebSockets or with it disabled, web-socket-js will be used. It will be less efficient than native, but still much lower latency than long-polling.
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
Reference:
Alternative to WebSockets
https://softwareengineering.stackexchange.com/questions/33713/is-there-an-alternative-to-html-web-sockets-now-that-firefox-4-has-disabled-the

I just wanted to share the actual implementation I went with. I decided to go with a great SAAS, Pusher, since there are many challenging issues in implementing Push notifications, as I realized in reading the links in #Virendra's excellent answer, that Pusher solves for you.
What I was most impressed with is how little code you have to write to make this work. See below.
My server-side is in PHP (Pusher has libraries in many languages).
require('/application/thirdParty/pusher-html5-realtime-push-notifications/lib/squeeks-Pusher-PHP/lib/Pusher.php');
require('/application/thirdParty/pusher-html5-realtime-push-notifications/config.php');
$pusher = new Pusher(APP_KEY, APP_SECRET, APP_ID);
foreach($recipients as $row){
$channel='my-channel'.$row->recipient_id;
$pusher->trigger($channel, 'notifications',
array('message' => $row->message,
'notification_id' => $row->notification_id)
);
}
Here's the HTML/JS (don't be overwhelmed, most of this code is just to populate the little circle and the list with the incoming notification as Stackoverflow and others do it):
<script src="/application/thirdParty/pusher.min.js"></script>
<script>
var myID=179; // would receive notification if myID matches $row->recipient_id above;
var myChannel = pusher.subscribe('my-channel'+myID);
myChannel.bind('notifications',
function(data) {
var message=String(data.message),
url='/notifications/'+data.notification_id,
icon='<i class=\'icon-heart\'></i>',
urlText=icon+message;
var notificationRow='<li><a href='+url+'>'+urlText+'</a></li>';
$('#notificationsDropdownList').prepend(notificationRow);
if(notificationCircleCount==0){
notificationCircleCount++;
$notificationCircle.show();
$notificationCircleCount.html(notificationCircleCount);
}
else{
notificationCircleCount++;
$notificationCircleCount.html(notificationCircleCount);
}
console.log('Pusher happened'+data.message);
} //function
); //myChannel
</script>

Related

jQuery and PHP - Comet

I've searched Google a lot. In all the examples having Comet with PHP and jQuery. They are doing:
setTimeout(function(){ check_new_data_function() }, 5000);
function check_new_data_function(){
$.ajax{
blah
}
}
And yes, it's pretty simple to use Comet with checks in every 5 seconds. But this could not be called "COMET" at all, isn't the purpose of Comet to not loop our requests? and instead get the data which is Pushed from server?
See this example.
Or another clip.
They are all having a function which gets the data from another file with $.ajax requests by looping. But are they really Long Polling/Comet?
As far as I knew when we didn't want to put the server under many $.ajax request which are looped, we would use Comet, in Comet the data is gonna Pushed from server to the client browser, was I wrong?
Could someone make this idea clear for me?
Can I Use on Web Sockets - Working Draft:
Partial support refers to the websockets implementation using an older
version of the protocol and/or the implementation being disabled by
default (due to security issues with the older protocol). Microsoft is
currently experimenting with the technology.
http://i.imgur.com/20X5z.png
The technology just isn't there yet. Watch this video from SymfonyLive if you want a better grasp on what the specs for HTTP and REST mean. It's interesting, and apparently Twitter goofed.
Also see:
http://en.wikipedia.org/wiki/Comparison_of_WebSocket_implementations

RealTime live notification Jquery PHP

I'm tried to implementing a live notification which is like the facebook newsticker and the notifications(on top). I was wondering what's the good solution to archieve this. I implemented an chat application before which I fired AJAX GET request in certain time to archieve the realtime, but it seems not good. I checked facebook using firebug, there is no GET request fired(or it is hided?)
Now here is my scenarion:
In main.php
I have a live ticker and a notifications button.
In bulletion.php and User.php
When I perform an add user,it will go heading to the bulletin or user.php.
How can I get informed in main.php when bulletin.php,user.php successfully created in database?
I checked this question as well before I asked.
notification system in PHP/jQuery
Realtime and php?
I was wonder,what's is long poling Ajax and session-based notification.How it can be archieved? I know Node.js can be good in implementing realtime, can it combine with PHP? and memcached ?
Any can provide sources to refer or example might be good.Thank you.
As a side note, PHP isn't really the best language to use when it comes to push notifications, it's really built around typical get/response kinda flows.
I use PHP for all my page stuff, but when it comes to push notifications of any sort I really like http://www.nodejs.org/ and http://socket.io/ to go with it. They're very easy to get setup, and will play well with you using php for the majority of your work, then using node to deal with push notification kinda stuff.
Have you thought about using HTML5 WebSockets? Have a look at EventSockets and the kickstart project on Github.
I've had much success with the server-sent events standard. It's very simple and works perfectly but it's only supported in modern browsers.
Meteor is a comet server using PHP and JavaScript to push data to browsers. It's very slick and worth a look, although it may be a little hard to setup/implement.
Edit: Quick demo here

Ajax response ? how to minimize ajax requests in a game

I am building a poker game via html/php/ajax (and some other stuff) NO-FLASH .
I have little experience in programming games , so i have small question !
assuming ur playing poker , how your browser will know that some player threw a card ?
shall my browser send ajax request to know if somebody made a move ??? or is there anyway to treat ajax->php like a socket ajax<->php ??
I hope someone understands my question , thanks
Depending on the amount of traffic you'll, face, a good idea is to use a Message Queue server, such as Apache ActiveMQ along with something to allow all browsers to connect to ActiveMQ and receive 'push' messages from it, on the lines of Orbited 2 - this one is prepared for changes on the websocket protocol as new reviews are generated (not sure a consensus over the protocol has been reached yet).
The best bet for you is to research a relatively old technology, but not widely used (I mean, when compared to Ajax) that is known both as Comet and Ajax Push.
It's obvious there are several other implementations, such as APE, and you would probably want to pick the one (whose programming language and/or API) you feel mostly comfortable with.

Push notification to the client browser

I'd like to create an application where when a Super user clicks a link the users should get a notification or rather a content like a pdf for them to access on the screen.
Use Case: When a teacher wants to share a PDF with his students he should be able to notify his students about the pdf available for download and a link has to be provided to do the same.
There are several ways you can accomplish this. The most supported way is through a technique called Comet or long-polling. Basically, the client sends a request to the server and the server doesn't send a response until some event happens. This gives the illusion that the server is pushing to the client.
There are other methods and technologies that actually allow pushing to the client instead of just simulating it (i.e. Web Sockets), but many browsers don't support them.
As you want to implement this in CakePHP (so I assume it's a web-based application), the user will have to have an 'active' page open in order to receive the push messages.
It's worth looking at the first two answers to this, but also just think about how other sites might achieve this. Sites like Facebook, BBC, Stackoverflow all use techniques to keep pages up to date.
I suspect Facebook just uses some AJAX that runs in a loop/timer to periodically pull updates in a way that would make it look like push. If the update request is often enough (short time period), it'll almost look realtime. If it's a long time period it'll look like a pull. Finding the right balance between up-to-dateness and browser/processor/network thrashing is the key.
The actual request shouldn't thrash the system, but the reply in some applications may be much bigger. In your case, the data in each direction is tiny, so you could make the request loop quite short.
Experiment!
Standard HTTP protocol doesn't allow push from server to client. You can emulate this by using for example AJAX requests with small interval.
Have a look at php-amqplib and RabbitMQ. Together they can help you implement AMQP (Advanced Message Queuing Protocol). Essentially your web page can be made to update by pushing a message to it.
[EDIT] I recently came across Pusher which I have implemented for a project. It is a HTML5 WebSocket powered realtime messaging service. It works really well and has a free bottom tier plan. It's also extremely simple to implement.
Check out node.js in combination with socket.io and express. Great starting point here

Simple comet example using php and jquery

Can anyone give me a good and simple example of the comet technique using PHP?
I just need an example that uses a persistent HTTP connection or something similar. I don't want to use a polling technique, because I have something like that set up and not only is it difficult to work with and manage its a big hog of resources. Also I am using IIS7 not Apache.
A good example would be really helpful so I can move on from this ugly polling technique.
You should use polling, or use a web server which is specially conceived for long requests and COMET, with a good JS backend:
function listen() {
$.get("/mylongrequestfile", {}, function(data) {
$("#mydiv").html(data);
listen(); // then launch again
}));
};
Remember that COMET is "wait for data, if there's data return and exit", so JS backend will have to parse the data and re-launch the process of asking the server.
In this example, if there is a server side problem or just a disconnection from the user side, the entire process will be broken (the function is only called if the request is successful)
Check this out: How to implement COMET with PHP.
This is not using JQuery. It is made using PHP and Prototype. It is very easy to understand. I think you can made JQuery script easily after viewing this.
I have a very simple example here that can get you started with comet. It covers compiling Nginx with the NHPM module and includes code for simple publisher/subscriber roles in jQuery, PHP, and Bash.
http://blog.jamieisaacs.com/2010/08/27/comet-with-nginx-and-jquery/
A working example (simple chat) can be found here:
http://cheetah.jamieisaacs.com/
Never having used this technique and studying the Wikipedia article on the topic, "Long Polling" seems like the only viable solution. It sounds pretty simple to implement by infinitely looping and sleeping a script on the server. There's some actual code in the HTTP Streaming page linked to from the Wikipedia article.
Have you tried any of this and stumbled on specific problems?
Check out this demo video for implementing Long Polling ( comet )..
It might help you all
http://www.screenr.com/SNH
You can take a look at this article, it's a really good start to understand comet programming concepts.
You will find two examples on it. The first one use the iframe technique whereas the second one use a persistent connection.
For IIS, there's WebSync. Since you're using PHP, however, you might be better off with WebSync On-Demand. Either one will give you the server-push you're looking for, and is simple to use. Check out this question as well, which is basically what you're after.
Here's a simple example of WebSync On-Demand in action using no scripting language. Simply open in two windows, and see the publish/subscribe in action.
To publish from the server, you can use the PHP api.

Categories