How To Connect To WebSockets With PHP

If you are using a WebSocket server from PieSocket, you are lucky because we let you publish messages to our WebSocket channels through a REST API as documented here: https://www.piesocket.com/docs/3.0/php

What about an external WebSocket channel, or what if for some reason you want to connect to the PieSocket channel through a PHP WebSocket client and not the REST API.

In this tutorial, we will create a script that runs in a Linux/Mac/Windows terminal and acts as a WebSocket client to connect to any WebSocket server.

For testing purposes, we will use PieSocket’s publicly available WebSocket Server

Let’s begin building our shiny new PHP WebSocket Client application.

Start by creating an empty directory for our project

Change working directory to the newly created project directory

For the next step, you need composer in your system, if you do not have it already, install composer.
Next, Install the “Textalk/websocket-php” library into your application

This will place composer.json and composer.lock files into your current directory and download dependencies into the vendor folder.

Now it’s time to create the script to connect to a WebSocket server.

We include the vendor/autolaod.php file to load the dependencies we downloaded using composer into our script.

Then, we connect to the WebSocket server and run an infinite loop so the script keeps running to listen to the incoming messages.

Time to run the script, open a terminal, and fire up the following command

You should see incoming messages in your terminal now.
You can use PieSocket’s WebSocket Tester to send messages to the WebSocket server and they should appear in your terminal.

You can find the source code shown above in this git repository: https://github.com/piesocket/php-websocket-client-example

Hope this helps, let us know your questions and feedback by leaving comments below!