You build a PHP messenger by implementing four layers in order: a database schema for conversations and messages, PHP endpoints that authenticate users and validate input, a polling loop that fetches new messages, and a front end that renders them. The critical condition is that every message must be tied to a verified membership check—if a user isn't in a conversation, no endpoint may return its contents. The rest is engineering discipline around ordering, concurrency, and failure handling. This guide walks through a complete, self-hosted implementation using PHP 8 and MySQL, with the source structure and key code for each piece.

The design here is deliberately modest: long-polling rather than WebSockets, server-rendered JSON, and no third-party services. It's the version you can actually finish and secure, and it's the right foundation before you reach for Ratchet or Swoole.

What stack and environment you need first

Before writing any code, confirm these prerequisites. Skipping them causes the confusing failures later.

PHP 8.1 or newer with the pdo_mysql extension enabled. Verify with php -m | grep pdo_mysql. MySQL 8.0 or MariaDB 10.6, with a database and a dedicated application user—not root. A web server (Apache or Nginx) with HTTPS configured. Cookies marked Secure won't work over plain HTTP, and messenger session cookies must be Secure and HttpOnly. Composer, if you want a router and a mail library; the core below needs neither. Write access for PHP sessions and logs, checked by confirming session_start() succeeds and writes to the configured save path.

A note on transport: PHP's shared-hosting execution model normally kills a request after 30 seconds, so long-polling must be capped below that limit. If you control the server (php-fpm, no proxy timeout), you can hold connections longer. Decide now, because it changes your client loop.

Design the database schema before writing endpoints

The schema is where most messenger bugs originate. Three tables cover the core, with a fourth for delivery state.

Three decisions deserve explanation. The composite index idx_conv_id makes the polling query fast because fetching "messages after ID X in conversation Y" is an index range scan. The client_uuid unique key provides idempotency: if a flaky network causes the client to retry a send, the database rejects the duplicate instead of posting the message twice. And last_read_message_id on the membership row gives you unread counts without a separate tracking table.

A caution about auto-increment IDs: they're not a reliable global ordering across concurrent inserts in strict timestamp terms, but within one conversation they're fine for pagination because each insert is atomic. Order by id, not created_at, for "after X" queries.

Implement authentication and session handling

Every endpoint begins with the same gate: verify the session, load the user, then verify conversation membership. Keep that in one file so you can't forget it.

Registration uses password_hash($plain, PASSWORD_DEFAULT) and login uses password_verify. Both are stable, documented functions in PHP 8; don't hand-roll hashing. Also regenerate the session ID on login with session_regenerate_id(true) to prevent session fixation.

Run every endpoint through require_login and require_member. The failure mode you're preventing is the most common messenger vulnerability: an endpoint that accepts a conversation ID but never checks whether the caller belongs to it. Test it explicitly by calling an endpoint with a foreign conversation ID and confirming a 403.

Build the registration, login, and conversation endpoints

Keep endpoints as separate PHP files or route them through a single front controller. Here's the shape of the three that matter most.

Registration (POST /register.php):

Starting a conversation (POST /conversations.php) creates the conversation and memberships in one transaction, because a conversation with no members is unusable:

Sending a message (POST /messages.php) checks membership, validates the body, and catches the duplicate-key exception to return the existing message instead of an error. Clients need to distinguish "your retry already landed" from "something broke," and a 409 with the original message ID gives them that.

Send a message safely: validation, idempotency, and transactions

The send path carries the most risk, so spell out its rules:

1: Decode JSON and reject if conversation_id, body, or client_uuid is missing. 2: Confirm membership with require_member. 3: Trim the body, reject empty or longer than 4,000 bytes, and store as UTF-8. 4: Attempt the insert; on error code 23000 (duplicate key), look up the existing row by client_uuid and return it with HTTP 200. 5: Return the stored row's id and created_at.

The success check is simple: send the same client_uuid twice in a row and confirm SELECT COUNT(*) FROM messages increments by exactly one. That's the whole point of the unique constraint, and it's easy to verify.

Fetch new messages with long-polling

The polling endpoint (GET /messages.php?conversation_id=X&after=Y&wait=20) returns messages with IDs greater than the client's cursor. The "long" part means it waits up to a safe ceiling before returning empty, which cuts request volume dramatically compared with fixed one-second polling.

Check two things in testing: that an empty response returns before your PHP max_execution_time fires, and that a message sent from another session appears within roughly wait seconds. If empty responses arrive after exactly 30 seconds with a 500 error, your wait cap or FPM timeout is misconfigured.

Two scaling notes. Each open poll holds one PHP worker, so concurrency equals roughly your php-fpm worker count. On shared hosting with few workers, lower the cap to 5–10 seconds. And for very high message volume, switch the inner fetch to keyset pagination with LIMIT 100 and have the client immediately re-poll when it receives a full page.

Render the messenger UI and wire up the client loop

The front end is one HTML page and a small script. Render the conversation list server-side, then let JavaScript handle sends and polling.

Using textContent instead of innerHTML is the single most important line here—it closes the stored-XSS hole that would otherwise let a message body execute script in every reader's browser. The crypto.randomUUID() call requires a secure context (HTTPS or localhost); that's another reason HTTPS is a prerequisite, not a nicety.

Note the client's failure behavior: on a failed send, the text stays in the input so the user can retry with the same or a new UUID. A messenger that silently drops typed messages is worse than one that shows an error.

Security, scale, and the limits of this design

Several hardening steps belong in the same build, not a later phase.

Output and input. Escape on render (as above), validate types at every boundary, and use prepared statements everywhere—the code here does, and there is no case where string concatenation into SQL is acceptable.

Rate limiting. A simple token bucket in a MySQL table or Redis keyed by user ID stops message floods. Without it, one client looping POST /messages.php can fill the table and hammer every reader's poll.

CSRF. Because the API uses a session cookie, state-changing requests need protection. Either require a custom header (which cross-origin forms can't set) or attach a per-session token. The SameSite=Lax cookie helps but isn't sufficient on its own for POST-heavy APIs.

Authorization testing. Write a two-user test: user A creates a conversation, user B tries to read and post to it, and both must fail with 403. Then add B as a member and confirm both succeed. This is the check that catches the class of bug that leaks private messages.

Scaling ceilings. Polling works to a few hundred concurrently connected users per server; beyond that, file descriptor and worker limits dominate. A WebSocket server such as Ratchet (still maintained for PHP 8) or an async runtime like Swoole moves you to push delivery. The schema above carries over unchanged, which is why it's worth getting right first. Push notifications to mobile and read receipts (using last_read_message_id) are natural next additions, as are message edits, which need a edited_at column and a rendering convention rather than mutation of history.

Deletion and retention. Decide early whether deleting a message is a soft delete with a deleted_at flag or a hard delete. Hard deletes break idempotency lookups if a client retries after deletion, so soft deletes are the safer default for a messenger.

The stop condition. If your requirements include end-to-end encryption, regulated data handling, or guaranteed delivery across network partitions, the polling design is the wrong foundation; those need a protocol and infrastructure decision made before code is written, ideally with someone experienced in secure messaging systems.

This build gets you a functional, reasonably safe messenger and, more important, a clear map of where each additional feature attaches. Start with the schema and the membership check, get a two-user conversation working end to end, then layer security and scale.

FAQ

Can I use SQLite instead of MySQL? Yes for development and small deployments. Replace the DSN and drop ENGINE=InnoDB. SQLite serializes writes, which is fine at low volume but becomes a bottleneck under concurrent sends; its lack of the exact duplicate-key error code handling shown above means you should test the idempotency path separately.

Should I use WebSockets from the start? Only if you already expect hundreds of simultaneously connected users or need typing indicators. Long-polling is simpler to deploy on standard PHP hosting, and the client loop swaps out without touching the database layer.

How do I handle message ordering when two users send at once? Order by the auto-increment id, which is assigned atomically at insert. Clients should never sort by timestamp, because millisecond clocks on different machines can disagree.

What about file and image attachments? Store the file outside the web root with a random name, keep metadata in a message_attachments table, and serve downloads through a PHP endpoint that runs the same membership check. Never serve uploads directly from a public directory.