WebSockets provide real-time bidirectional communication between clients and servers, but running WebSockets on shared hosting is difficult because shared hosting environments have strict limitations on long-running scripts and background processes.
php websocket.php).Since traditional WebSockets require persistent processes and custom ports, you can try these alternatives:
Instead of running WebSockets directly, use a WebSocket relay service. Your PHP application on shared hosting pushes events to an external service, which then broadcasts them to connected clients via real WebSockets.
Example Services:
Example Using Pusher (Recommended for Shared Hosting)
First, install the Pusher PHP library via Composer: composer require pusher/pusher-php-server
<?php
require 'vendor/autoload.php';
$pusher = new Pusher\Pusher(
'your-app-key',
'your-app-secret',
'your-app-id',
[
'cluster' => 'your-cluster',
'useTLS' => true
]
);
// Send WebSocket event
$pusher->trigger('my-channel', 'my-event', ['message' => 'Hello World']);
?>
Pros: No need for WebSocket servers on shared hosting; reliable and scalable.
Cons: Requires an external service (often has free tiers).
If your shared hosting allows custom Apache or Nginx configuration, you might proxy WebSocket traffic to an external WebSocket server you run elsewhere (e.g., a cheap VPS). This is rarely possible on shared hosting.
Apache WebSocket Proxy Configuration (via .htaccess)
If your host allows mod_proxy_wstunnel in .htaccess:
RewriteEngine On
RewriteCond %{HTTP:Upgrade} =websocket [NC]
RewriteRule ^/(.*) ws://your-external-websocket-server.com:8080/$1 [P,L]
Pros: Can work if WebSocket proxying is explicitly supported.
Cons: Over 99% of shared hosting providers disable this for security.
If WebSockets aren't possible, long polling (AJAX requests that keep connections open) can simulate real-time updates.
Backend (server.php)
<?php
session_start();
$lastUpdate = $_SESSION['last_update'] ?? 0;
// Prevent script timeout on some hosts
set_time_limit(60);
while (true) {
clearstatcache();
$currentUpdate = filemtime('data.txt'); // Check for file changes
if ($currentUpdate > $lastUpdate) {
$_SESSION['last_update'] = $currentUpdate;
echo json_encode(['message' => file_get_contents('data.txt')]);
flush();
exit;
}
sleep(2); // Check every 2 seconds
}
?>
Frontend (client.js)
function pollServer() {
fetch('server.php')
.then(response => response.json())
.then(data => {
console.log("New message: ", data.message);
pollServer(); // Keep polling
})
.catch(() => setTimeout(pollServer, 5000)); // Retry on error
}
pollServer();
Pros: Works on all shared hosting without special requirements.
Cons: Higher latency, more server load, less efficient than WebSockets.
If you must use real WebSockets with PHP, you need VPS hosting where you can run persistent processes.
Install a PHP WebSocket Server (Ratchet) on VPS
composer require cboden/ratchet
WebSocket Server (server.php)
<?php
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\App;
class ChatServer implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
echo "New connection ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} closed\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "Error: {$e->getMessage()}\n";
$conn->close();
}
}
$server = new App('localhost', 8080);
$server->route('/chat', new ChatServer, ['*']);
$server->run();
?>
Run the server (via SSH on VPS):
php server.php
Keep it running: Use screen, tmux, or a process manager like supervisord.
Pros: Real WebSockets with full control.
Cons: Requires VPS (not shared hosting) and server administration.
| Method | Works on Shared Hosting? | Pros | Cons |
|---|---|---|---|
| Pusher / External Service | Yes | Easy setup, reliable, scalable | Third-party dependency, potential cost |
| WebSocket Proxy | Maybe | Direct WebSocket connection if supported | Almost always blocked on shared hosting |
| Long Polling with PHP | Yes | No external services, works everywhere | High latency, inefficient, server load |
| Upgrade to VPS | No | Full WebSocket support, complete control | More expensive, requires sysadmin skills |