I'll provide a comprehensive approach to implementing real-time notifications in CodeIgniter 3 using multiple methods:
Method 1: WebSockets with Socket.IO
Server-Side (Node.js)
// server.js
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// Store connected users
const connectedUsers = {};
io.on('connection', (socket) => {
// When a user connects
socket.on('register', (userId) => {
connectedUsers[userId] = socket.id;
console.log(`User ${userId} connected`);
});
// Send notification to specific user
socket.on('send_notification', (data) => {
const targetSocketId = connectedUsers[data.userId];
if (targetSocketId) {
io.to(targetSocketId).emit('new_notification', {
message: data.message,
type: data.type
});
}
});
// Disconnect handling
socket.on('disconnect', () => {
for (let userId in connectedUsers) {
if (connectedUsers[userId] === socket.id) {
delete connectedUsers[userId];
break;
}
}
});
});
server.listen(3000, () => {
console.log('Socket server running on port 3000');
});
CodeIgniter Controller
// application/controllers/Notifications.php
class Notifications extends CI_Controller {
public function send_real_time_notification() {
// Ensure only authorized users can send notifications
if (!$this->ion_auth->is_admin()) {
show_error('Unauthorized');
}
$user_id = $this->input->post('user_id');
$message = $this->input->post('message');
// Save to database
$notification_data = [
'user_id' => $user_id,
'message' => $message,
'type' => 'real_time',
'created_at' => date('Y-m-d H:i:s'),
'is_read' => 0
];
$this->db->insert('notifications', $notification_data);
// Trigger external notification service
$this->trigger_socket_notification($user_id, $message);
redirect('admin/dashboard');
}
private function trigger_socket_notification($user_id, $message) {
// Use Guzzle or cURL to send to Node.js server
$client = new GuzzleHttp\Client();
$client->post('http://localhost:3000/send_notification', [
'json' => [
'userId' => $user_id,
'message' => $message
]
]);
}
}
Frontend JavaScript
// In your view
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
// Connect to Socket.IO server
const socket = io('http://localhost:3000');
// Register current user
socket.emit('register', <?php echo $this->ion_auth->user()->row()->id; ?>);
// Listen for notifications
socket.on('new_notification', function(data) {
// Display toast or desktop notification
showNotification(data.message);
// Update notification count
updateNotificationBadge();
});
function showNotification(message) {
// Use browser notifications or custom toast
if (Notification.permission === 'granted') {
new Notification('New Notification', {
body: message
});
} else if (Notification.permission !== 'denied') {
Notification.requestPermission().then(function(permission) {
if (permission === 'granted') {
new Notification('New Notification', {
body: message
});
}
});
}
// Alternatively, use a toast library
toastr.success(message);
}
function updateNotificationBadge() {
$.ajax({
url: '<?php echo site_url("notifications/get_unread_count"); ?>',
method: 'GET',
success: function(count) {
$('.notification-badge').text(count);
}
});
}
});
</script>
Method 2: Long Polling Alternative
Controller
class Notifications extends CI_Controller {
public function long_poll() {
$user_id = $this->ion_auth->user()->row()->id;
$last_check = $this->input->get('last_check');
// Set timeout and start time
$timeout = 30; // 30 seconds
$start = time();
// Keep checking for new notifications
while (time() - $start < $timeout) {
$new_notifications = $this->db->query("
SELECT * FROM notifications
WHERE user_id = ? AND created_at > ?
AND is_read = 0
", [$user_id, $last_check])->result();
if (!empty($new_notifications)) {
echo json_encode($new_notifications);
exit;
}
// Sleep to prevent high CPU usage
sleep(5);
}
// No new notifications
echo json_encode([]);
}
}
Frontend Long Polling
function startLongPolling() {
let lastCheck = new Date().toISOString();
function poll() {
$.ajax({
url: '<?php echo site_url("notifications/long_poll"); ?>',
data: { last_check: lastCheck },
method: 'GET',
timeout: 35000, // Slightly longer than server timeout
success: function(notifications) {
if (notifications.length > 0) {
notifications.forEach(function(notification) {
showNotification(notification.message);
});
lastCheck = new Date().toISOString();
}
},
complete: function() {
// Restart polling
poll();
},
error: function() {
// Exponential backoff
setTimeout(poll, 5000);
}
});
}
poll();
}
Method 3: Server-Sent Events (SSE)
Controller
class Notifications extends CI_Controller {
public function sse() {
// Disable output buffering
if (ob_get_level()) {
ob_end_clean();
}
// Set headers for SSE
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-open');
$user_id = $this->ion_auth->user()->row()->id;
$last_id = 0;
while (true) {
// Check for new notifications
$notifications = $this->db->query("
SELECT * FROM notifications
WHERE id > ? AND user_id = ?
AND is_read = 0
", [$last_id, $user_id])->result();
if (!empty($notifications)) {
foreach ($notifications as $notification) {
echo "data: " . json_encode($notification) . "\n\n";
$last_id = $notification->id;
flush();
}
}
// Prevent high CPU usage
sleep(5);
// Optional: Break connection after certain time
if (connection_aborted()) {
break;
}
}
}
}
Frontend SSE
function startSSE() {
const eventSource = new EventSource('<?php echo site_url("notifications/sse"); ?>');
eventSource.onmessage = function(event) {
const notification = JSON.parse(event.data);
showNotification(notification.message);
};
eventSource.onerror = function() {
// Reconnect
eventSource.close();
setTimeout(startSSE, 5000);
};
}
Recommended Approach
- WebSockets (Socket.IO): Best for real-time, low-latency notifications
- Long Polling: Good fallback for older browsers
- Server-Sent Events: Good for unidirectional real-time updates
Additional Considerations
-
Security
- Validate user authentication for all real-time methods
- Use secure WebSocket connections (wss://)
- Implement proper access controls
-
Performance
- Use connection pooling
- Implement caching
- Optimize database queries
-
Scalability
- Consider using Redis for managing WebSocket connections
- Implement horizontal scaling for notification services
Dependencies
- Install Node.js and npm
- Install Socket.IO:
npm install socket.io express
- Install Guzzle for PHP:
composer require guzzlehttp/guzzle
Recommendation
For CodeIgniter 3, I recommend the Socket.IO approach with a fallback to long polling. It provides the most responsive and reliable real-time notification system.
Would you like me to elaborate on any specific aspect of real-time notifications?