DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • The Role of JavaScript in Front-End and Back-End Development
  • A Multilingual Prestashop Online Store Using ChatGPT
  • A Step-By-Step Guide: How To Install a Laravel Script
  • PHP or ASP.NET: Which Powerhouse Platform Prevails for Your Next Project?

Trending

  • Supercharging Productivity in Microservice Development With AI Tools
  • Automate Migration Assessment With XML Linter
  • Breaking Free From the Cloud With Kamal: Just Enough Orchestration for Your Apps
  • Send Your Logs to Loki
  1. DZone
  2. Coding
  3. Languages
  4. Real Time Notifications With PHP

Real Time Notifications With PHP

Gonzalo Ayuso user avatar by
Gonzalo Ayuso
·
Mar. 14, 11 · News
Like (0)
Save
Tweet
Share
66.87K Views

Join the DZone community and get the full member experience.

Join For Free
real time communications are cool, isn’t it? something impossible to do five years ago now (or almost impossible) is already available. nowadays we have two possible solutions. websockets and comet. websockets are probably the best solution but they’ve got two mayor problems:
  • not all browsers support them.
  • not all proxy servers allows the communications with websokets.

because of that i prefer to use comet (at least now). it’s not as good as websockets but pretty straightforward ant it works (even on ie). now i’m going to explain a little script that i’ve got to perform a comet communications, made with php. probably it’s not a good idea to use it in a high traffic site, but it works like a charm in a small intranet. if you want to use comet in a high traffic site maybe you need have a look to tornado , twisted , node.js or other comet dedicated servers.

normally when we are speaking about real-time communications, all the people are thinking about a chat application. i want to build a simpler application. a want to detect when someone clicks on a link. because of that i will need a combination of html, php and javascript. let’s start:

for the example i’ll use jquery library, so we need to include the library in our html file. it will be a blend of javascrip and php:

<html>
02 <head>
03 <meta http-equiv="content-type" content="text/html; charset=utf-8">
04 <title>comet test</title>
05 </head>
06 <body>
07 <p><a class='customalert' href="#">publish customalert</a></p>
08 <p><a class='customalert2' href="#">publish customalert2</a></p>
09 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
10 <script src="novcomet.js" type="text/javascript"></script>
11 <script type="text/javascript">
12 novcomet.subscribe('customalert', function(data){
13 console.log('customalert');
14 //console.log(data);
15 }).subscribe('customalert2', function(data){
16 console.log('customalert2');
17 //console.log(data);
18 });
19
20 $(document).ready(function() {
21 $("a.customalert").click(function(event) {
22 novcomet.publish('customalert');
23 });
24
25 $("a.customalert2").click(function(event) {
26 novcomet.publish('customalert2');
27 });
28 novcomet.run();
29 });
30 </script>
31 </body>
32 </html>


the client code:

//novcomet.js
02 novcomet = {
03 sleeptime: 1000,
04 _subscribed: {},
05 _timeout: undefined,
06 _baseurl: "comet.php",
07 _args: '',
08 _urlparam: 'subscribed',
09
10 subscribe: function(id, callback) {
11 novcomet._subscribed[id] = {
12 cbk: callback,
13 timestamp: novcomet._getcurrenttimestamp()
14 };
15 return novcomet;
16 },
17
18 _refresh: function() {
19 novcomet._timeout = settimeout(function() {
20 novcomet.run()
21 }, novcomet.sleeptime);
22 },
23
24 init: function(baseurl) {
25 if (baseurl!=undefined) {
26 novcomet._baseurl = baseurl;
27 }
28 },
29
30 _getcurrenttimestamp: function() {
31 return math.round(new date().gettime() / 1000);
32 },
33
34 run: function() {
35 var cometcheckurl = novcomet._baseurl + '?' + novcomet._args;
36 for (var id in novcomet._subscribed) {
37 var currenttimestamp = novcomet._subscribed[id]['timestamp'];
38
39 cometcheckurl += '&' + novcomet._urlparam+ '[' + id + ']=' +
40 currenttimestamp;
41 }
42 cometcheckurl += '&' + novcomet._getcurrenttimestamp();
43 $.getjson(cometcheckurl, function(data){
44 switch(data.s) {
45 case 0: // sin cambios
46 novcomet._refresh();
47 break;
48 case 1: // trigger
49 for (var id in data['k']) {
50 novcomet._subscribed[id]['timestamp'] = data['k'][id];
51 novcomet._subscribed[id].cbk(data.k);
52 }
53 novcomet._refresh();
54 break;
55 }
56 });
57
58 },
59
60 publish: function(id) {
61 var cometpublishurl = novcomet._baseurl + '?' + novcomet._args;
62 cometpublishurl += '&publish=' + id;
63 $.getjson(cometpublishurl);
64 }
65 };


the server-side php

// comet.php
02 include('novcomet.php');
03
04 $comet = new novcomet();
05 $publish = filter_input(input_get, 'publish', filter_sanitize_string);
06 if ($publish != '') {
07 echo $comet->publish($publish);
08 } else {
09 foreach (filter_var_array($_get['subscribed'], filter_sanitize_number_int) as $key => $value) {
10 $comet->setvar($key, $value);
11 }
12 echo $comet->run();
13 }


and my comet library implementation:

// novcomet.php
02 class novcomet {
03 const comet_ok = 0;
04 const comet_changed = 1;
05
06 private $_tries;
07 private $_var;
08 private $_sleep;
09 private $_ids = array();
10 private $_callback = null;
11
12 public function __construct($tries = 20, $sleep = 2)
13 {
14 $this->_tries = $tries;
15 $this->_sleep = $sleep;
16 }
17
18 public function setvar($key, $value)
19 {
20 $this->_vars[$key] = $value;
21 }
22
23 public function settries($tries)
24 {
25 $this->_tries = $tries;
26 }
27
28 public function setsleeptime($sleep)
29 {
30 $this->_sleep = $sleep;
31 }
32
33 public function setcallbackcheck($callback)
34 {
35 $this->_callback = $callback;
36 }
37
38 const default_comet_path = "/dev/shm/%s.comet";
39
40 public function run() {
41 if (is_null($callback)) {
42 $defaultcometpath = self::default_comet_path;
43 $callback = function($id) use ($defaultcometpath) {
44 $cometfile = sprintf($defaultcometpath, $id);
45 return (is_file($cometfile)) ? filemtime($cometfile) : 0;
46 };
47 } else {
48 $callback = $this->_callback;
49 }
50
51 for ($i = 0; $i < $this->_tries; $i++) {
52 foreach ($this->_vars as $id => $timestamp) {
53 if ((integer) $timestamp == 0) {
54 $timestamp = time();
55 }
56 $filetimestamp = $callback($id);
57 if ($filetimestamp > $timestamp) {
58 $out[$id] = $filetimestamp;
59 }
60 clearstatcache();
61 }
62 if (count($out) > 0) {
63 return json_encode(array('s' => self::comet_changed, 'k' => $out));
64 }
65 sleep($this->_sleep);
66 }
67 return json_encode(array('s' => self::comet_ok));
68 }
69
70 public function publish($id)
71 {
72 return json_encode(touch(sprintf(self::default_comet_path, $id)));
73 }
74 }

as you can see in my example i’ve created a personal protocol for the communications between the client (js at browser), and the server (php). it’s a simple one. if you’re looking for a “standard” protocol maybe you need have a look to bayeux protocol from dojo people.

let me explain a little bit the usage of the script:

  • in the html page we start the listener (novcomet.subscribe).
  • we can subscribe to as many events we want (ok it depends on our resources)
  • when we subscribe to one event we pass a callback function to be triggered.
  • when we subscribe to the event, we pass the current timestamp to the server.
  • client side script (js with jquery) will call to server-side script (php) with the timestamp and will wait until server finish.
  • server side script will answer when even timestamp changes (someone has published the event)
  • server side will no keep waiting forever. if nobody publish the event, server will answer after a pre-selected timeout
  • client side script will repeat the process again and again.

there’s something really important with this technique. our server-side event check need to be as simpler as we can. we cannot execute a sql query for example (our sysadmin will kill us if we do it). we need to bear in mind that this check will be performed again and again per user, because of that it must be as light as we can. in this example we are checking the last modification date of a file ( filemtime ). another good solution is to use a memcached database and check a value.

for the test i’ve also created a publishing script (novcomet.publish). this is the simple part. we only call a server-side script that touch the event file (changing the last modification date), triggering the event.

now i’m going to explain what we can see on the firebug console:

  1. the first iteration nothing happens. 200 ok http code after the time-out set in the php script
  2. as we can see here the script returns a json with s=0 (nothing happens)
  3. now we publish an event. script returns a 200 ok but now the json is different. s=1 and the time-stamp of the event
  4. our callback has been triggered
  5. and next iteration waiting

and that’s all. simple and useful. but remember, you must take care if you are using this solution within a high traffic site. what do you think? do you use lazy comet with php in production servers or would you rather another solution?

you can get the code at github here .

PHP

Published at DZone with permission of Gonzalo Ayuso, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Role of JavaScript in Front-End and Back-End Development
  • A Multilingual Prestashop Online Store Using ChatGPT
  • A Step-By-Step Guide: How To Install a Laravel Script
  • PHP or ASP.NET: Which Powerhouse Platform Prevails for Your Next Project?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: