Era Host hosting
EraHost – Free Domain, Cheap Hosting!
Client Area
Support 24/7
Menu

Running PHP WebSockets on Shared Hosting — Challenges & Workarounds

4 min read
22.05.2025

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.
Linux VDS
High performance for your projects
  • Root access and flexible setup
  • Control panel
  • NVMe disks
  • DDR5
Linux VDS

Workarounds for Running WebSockets on Shared Hosting

Since traditional WebSockets require persistent processes and custom ports, you can try these alternatives:

PHP WebSockets Shared Hosting Challenges
WebSockets need persistent processes — shared hosting kills them.

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
Bottom Line:
? 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.
Frequently asked questions
A few permissive shared hosts allow background processes via cron-restart tricks (cron starts a daemon, then exits; daemon keeps running until it crashes or the host kills it). It's fragile — host kills it during the weekly process sweep. Not a production solution. If you genuinely need WebSockets, budget for a $5/month VPS instead of fighting shared hosting.
Yes — and often the right answer for shared-hosting users. Your PHP talks to Pusher's HTTP API to publish events; Pusher handles the WebSocket connections to clients. Free tiers cover a few hundred concurrent connections; paid above. No infrastructure, no daemons, your shared host stays happy. Trade-off: monthly cost + vendor lock-in.
SSE is server-to-client only (no client→server), so it covers half of use cases — notifications, live feeds. PHP-FPM's typical max_execution_time kills the SSE connection after 30-60s, requiring client reconnect. Some shared hosts cap it at 30s with no override. For real-time but read-only use cases, SSE plus reconnect-on-disconnect can be enough.
Long-polling (XHR with 30s timeout, reconnect) works on every host but uses ~10x the resources for the same chat-room concurrency. For < 50 simultaneous users, fine. Past that, WebSocket's persistent connection model wins decisively. The break-even point is when WebSocket VPS cost exceeds the bandwidth/CPU cost of long-polling — almost always WebSocket wins for serious chat or live trading apps.
Related articles
Set PHP memory_limit = -1 via Command Line (For CLI Scripts)
MySQL Error #1227: Access Denied — You Need (at Least One of) the SUPER Privilege(s)
How to Configure Name Servers for Hosting (NSHosting Guide)