Running PHP WebSockets on Shared Hosting — Challenges & Workarounds
Challenges of Running WebSockets on Shared Hosting
- No Persistent Processes > Most shared hosts kill long-running PHP scripts (typically after 30-300 seconds).
- No Custom Ports > WebSockets require a dedicated port (e.g., 8080), but shared hosting restricts access to ports 80 and 443 only.
- Limited SSH Access > You can't run or keep a background process alive (e.g.,
php websocket.php). - Firewall Restrictions > Many shared hosts block WebSocket (WS/WSS) connections for security.
Workarounds for Running WebSockets on Shared Hosting
Since traditional WebSockets require persistent processes and custom ports, you can try these alternatives:
For closely related "PHP runtime on shared hosting" topics, see Fix shell_exec() Has Been Disabled and Fix proc_open() Has Been Disabled.
Use a WebSocket-as-a-Service Provider (Recommended)
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:
- Pusher (easiest for beginners)
- Ably
- Firebase Realtime Database
- Socket.IO with a cloud Node.js server
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).
Use a WebSocket Proxy (Reverse Proxy with Nginx/Apache)
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.
Use Long Polling Instead of WebSockets (Pure PHP)
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.
Upgrade to VPS or Dedicated Hosting (For Real 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.
Summary & Recommendation
| 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 |
? For shared hosting: Use Pusher (or similar service) for real-time features. It's the most reliable and performant workaround.
? For real WebSockets: Upgrade to a VPS and run Ratchet or a Node.js WebSocket server.


