websocket - PHP simple web socket client
Solution:
I had a similar task as you described in the topic. Basically I needed a PHP client to connect with my Socket.IO v4.4.1 server (Node.js with SSL/TLS). And here is a working code example:
// random 7 chars digit/alphabet for "t" param
$random = substr(md5(mt_rand()), 0, 7);
$socket_server='https://my-nodejs.server/socket.io/?EIO=4&transport=polling&t='.$random;
// create curl resource
$ch = curl_init();
//N°1 GET request
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server,
CURLOPT_RETURNTRANSFER => TRUE,
// since it is TRUE by default we should disable it
// on our localhost, but from real https server it will work with TRUE
CURLOPT_SSL_VERIFYPEER => FALSE
]);
// $output contains the output string
$output = curl_exec($ch);
$output=substr($output, 1);
echo $socket_server;
// server response in my case was looking like that:
// '{"sid":"4liJK2jWEwmTykwjAAAR","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}'
var_dump($output);
$decod=json_decode($output);
// setting ping Interval accordingly with server response
$pingInterval = $decod->pingInterval;
//N°2 POST request
$socket_server_with_sid = $socket_server.'&sid='.$decod->sid;
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_POST => TRUE,
CURLOPT_TIMEOUT_MS => $pingInterval,
// 4 => Engine.IO "message" packet type
// 0 => Socket.IO "CONNECT" packet type
CURLOPT_POSTFIELDS => '40'
]);
$output = curl_exec($ch);
// ok
var_dump($output);
// Pervious 2 requests are called "hand shake" now we can send a message
// N°3 socket.emit
if ($output==='ok') {
curl_setopt_array(
$ch,
[
CURLOPT_URL => $socket_server_with_sid,
CURLOPT_TIMEOUT_MS => $pingInterval,
CURLOPT_POST => TRUE,
// 4 => Engine.IO "message" packet type
// 2 => Engine.IO "EVENT" packet type
CURLOPT_POSTFIELDS => '42["chat message","0devhost message 10"]'
]);
$output = curl_exec($ch);
// ok
echo $output.'<br/>';
echo $socket_server_with_sid;
}
// close curl resource to free up system resources
curl_close($ch);
If you execute the code on your PHP server with https protocol, you can just comment out CURLOPT_SSL_VERIFYPEER param.
I simulated these requests with the POSTMAN, and it worked as well (don't forget to make all 3 request in a short time frame "ping interval", otherwise it will be automatically closed):
Links that helped me to come up to the solution and could be helpful for you as well:
Answer
Solution:
Connecting to a web socket server from php, requires to perform a handshake and to send your data in frames as defined by RFC6455. You can go to https://github.com/napengam/phpWebSocketServer and look into directory phpClient, there I have implemented a class to do all the above. This works with my web socket server, but it would be interesting to see if it will work with another web socket server. You might need to modify method writeWait, to not wait for an answer from the server. Good luck.
Source