I want to implement a website that has different types of users. I want that when a user posts something, the admin will be notified automatically. I have read about WebSockets and found some examples but mostly of them are about chat application. I just want a notification update. I just want to have a simple one.

Hope you can help me with this.

Dani AI

Generated

If you just need a simple, targeted notification (admin only, or a specific user), you do not have to jump straight to WebSockets. A lightweight option is Server-Sent Events (SSE): the browser opens a single HTTP connection and your PHP script streams events to that specific logged-in user. It is one-way (server -> client), which matches a notification use case and is much simpler to deploy than a full socket stack. See MDN for the basics of SSE if you want a deeper primer. Using server-sent events

Below is a minimal SSE endpoint in PHP. It checks the session, then polls a notifications table for new rows for the current user and streams them. Insert a row for user_id = <admin_id> when someone posts, or for any specific recipient you need.

<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(401); exit; }

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('X-Accel-Buffering: no'); // nginx
ignore_user_abort(true);

$uid = (int) $_SESSION['user_id'];
$lastId = 0;
$pdo = new PDO('mysql:host=...;dbname=...', 'user', 'pass', [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

while (!connection_aborted()) {
  $stmt = $pdo->prepare(
    'SELECT id, message FROM notifications
     WHERE user_id = ? AND id > ? ORDER BY id ASC'
  );
  $stmt->execute([$uid, $lastId]);

  foreach ($stmt as $row) {
    $lastId = (int) $row['id'];
    echo "id: {$lastId}\n";
    echo "event: notify\n";
    echo 'data: ' . json_encode(['message' => $row['message']]) . "\n\n";
    @ob_flush(); flush();
  }
  sleep(2);
}

Client side is tiny:

const es = new EventSource('/sse.php');
es.addEventListener('notify', e => {
  const { message } = JSON.parse(e.data);
  // TODO: show toast/badge and maybe refetch the relevant list
});

If you later need true bidirectional messaging or many concurrent connections, switch to a PHP WebSocket server like Ratchet. Ratchet on GitHub

Recommended Answers

All 5 Replies

Member Avatar for Member #120589

Websockets can certainly do that or you could use a Comet server (push). However Comet has its cons. Meteor may be a solution http://meteorserver.org/ but not striclty php.

socket.io has some nice examples too. If I were to implement something like push notifications, I would probably start experimenting with this.

Push notifications are very similar to what goes on in chat apps, so the faact that you see those as the main examles is not surprising.

I really don't have any idea how to implement that one. My main problem is the connection between the admin and a normal user. I want a specific client to be updated as well whenever the admin updates something. I don't want all the logged in user to be notified.

I have read about Comet too but I don't know how to implement it.

Member Avatar for Member #120589

Comet does look pretty fiddly to set up. I once tried to implement it from the APE site, but I failed miserably. I'd have a little play with the socket.io version and see how far you get. Then when you hit the wall with regard to user access come back. I'm sure that other people have tried what you're trying and there will be forums and tutorials online. I haven't seaarched for them, but i'd be very very surprised if there aren't any.

I've not been able to find much on socket.io and PHP, so perhaps wesockets would be better:

http://www.websocket.org/demos.html

If you want real help, rather than some opinions on how to approach the problem, then post your code here!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.