How can Javascript client connect to PHp socket Server?

php websocket client
socket io php
php websocket chat server example
websocket php
php socket connect
how to run websocket in php
php test socket connection

Hi I have a running socket server written with PHP.

The server is listening for connections.. any idea how my client(written in javascript) is going to connect to the server and send data to it?

PS: I only know how to connect a php client to the socket server but unsure how to connect a javascript client.

Thanks all for your time.

Shortly saying - you can't do that - it would be a security breach to let client side code open socket connections.

However, you could simulate that - send your data to another PHP page as an AJAX request, then make that PHP page communicate through the socket.

Update 2017:

In the mean time, websockets became a thing. Please note that the websocket protocol is a different thing than generic networking sockets

PHP and HTML5 WebSocket server and client communication, The problem comes when I try to connect the client in Javascript, both client and server, I think maybe I can't use PHP on the server  Copy above code and create HTML file, socket_client.html. After that execute following commands. nohup php -q socket_server.php & Above command will start your socket server. Now open HTML file in browser and it will connect to socket server. You are all set to use you PHP socket server. Related Reading

Answering an old question in case people find it as I did via Google.

Nowadays nearly all contemporary browsers support the WebSocket Javascript API. Via WS it's possible for client JS in the browser to open full duplex sockets to severs written in PHP or other languages. The server must implement the WS protocol, but there are WS libraries now for PHP, Java, and other languages.

At this moment of writing, WS implementations still seem like a bit of a moving target, but, I'm currently working with WS/JS browser clients communicating with a WS/Java server and it does seem to be working.

Suggest Googling for WS implementations in your server language of choice.

Hope this helps!

Is it possible to make work, using PHP on server-side , Then I thought of using with Node+PHP and with my research I came In same newly created directory, create a file server.js with these contents: io.​on('connection', function (socket){ var nb = 0;'SocketIO > Connected socket ' + '/vendor/autoload.php'; use ElephantIO\Client; use  I have server A "windows 7 Pro" where I installed node.js and ran it using this command node ws_server.js following the instructions here. From server B "Windows Server 2008 R2" running Apache 2.4/php 5.6.13 I want to connect to the ws_server on Server A.

I use standard WebSocket API for client. And core PHP socket for server side.

know, send and received data use a header on the browser with websocket. But the code PHP socket, send and received without header and just send plain data.

So we need to simulate header on the socketing server side.

For learning and know how do it, I write this clear sample code, With this code you can send a phrase to server and receive reverse phrase that in client.


//Code by: Nabi KAZ <>

// set some variables
$host = "";
$port = 5353;

// don't timeout!

// create socket
$socket = socket_create(AF_INET, SOCK_STREAM, 0)or die("Could not create socket\n");

// bind socket to port
$result = socket_bind($socket, $host, $port)or die("Could not bind to socket\n");

// start listening for connections
$result = socket_listen($socket, 20)or die("Could not set up socket listener\n");

$flag_handshake = false;
$client = null;
do {
    if (!$client) {
        // accept incoming connections
        // client another socket to handle communication
        $client = socket_accept($socket)or die("Could not accept incoming connection\n");

    $bytes =  @socket_recv($client, $data, 2048, 0);
    if ($flag_handshake == false) {
        if ((int)$bytes == 0)
        //print("Handshaking headers from client: ".$data."\n");
        if (handshake($client, $data, $socket)) {
            $flag_handshake = true;
    elseif($flag_handshake == true) {
        if ($data != "") {
            $decoded_data = unmask($data);
            print("< ".$decoded_data."\n");
            $response = strrev($decoded_data);
            socket_write($client, encode($response));
            print("> ".$response."\n");
            $client = null;
            $flag_handshake = false;
} while (true);

// close sockets

function handshake($client, $headers, $socket) {

    if (preg_match("/Sec-WebSocket-Version: (.*)\r\n/", $headers, $match))
        $version = $match[1];
    else {
        print("The client doesn't support WebSocket");
        return false;

    if ($version == 13) {
        // Extract header variables
        if (preg_match("/GET (.*) HTTP/", $headers, $match))
            $root = $match[1];
        if (preg_match("/Host: (.*)\r\n/", $headers, $match))
            $host = $match[1];
        if (preg_match("/Origin: (.*)\r\n/", $headers, $match))
            $origin = $match[1];
        if (preg_match("/Sec-WebSocket-Key: (.*)\r\n/", $headers, $match))
            $key = $match[1];

        $acceptKey = $key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
        $acceptKey = base64_encode(sha1($acceptKey, true));

        $upgrade = "HTTP/1.1 101 Switching Protocols\r\n".
            "Upgrade: websocket\r\n".
            "Connection: Upgrade\r\n".
            "Sec-WebSocket-Accept: $acceptKey".

        socket_write($client, $upgrade);
        return true;
    } else {
        print("WebSocket version 13 required (the client supports version {$version})");
        return false;

function unmask($payload) {
    $length = ord($payload[1]) & 127;

    if ($length == 126) {
        $masks = substr($payload, 4, 4);
        $data = substr($payload, 8);
    elseif($length == 127) {
        $masks = substr($payload, 10, 4);
        $data = substr($payload, 14);
    else {
        $masks = substr($payload, 2, 4);
        $data = substr($payload, 6);

    $text = '';
    for ($i = 0; $i < strlen($data); ++$i) {
        $text .= $data[$i] ^ $masks[$i % 4];
    return $text;

function encode($text) {
    // 0x1 text frame (FIN + opcode)
    $b1 = 0x80 | (0x1 & 0x0f);
    $length = strlen($text);

    if ($length <= 125)
        $header = pack('CC', $b1, $length);
    elseif($length > 125 && $length < 65536)$header = pack('CCS', $b1, 126, $length);
    elseif($length >= 65536)
    $header = pack('CCN', $b1, 127, $length);

    return $header.$text;


//Code by: Nabi KAZ <>

var socket = new WebSocket('ws://localhost:5353');

// Open the socket
socket.onopen = function(event) {
    var msg = 'I am the client.';

    console.log('> ' + msg);

    // Send an initial message

    // Listen for messages
    socket.onmessage = function(event) {
        console.log('< ' +;

    // Listen for socket closes
    socket.onclose = function(event) {
        console.log('Client notified socket has closed', event);

    // To close the socket....

<p>Please check the console log of your browser.</p>

Manual: first run php server.php on CLI and then open http://localhost/client.htm on browser.

You can see result:

> I am the client.
< .tneilc eht ma I

php server.php
< I am the client.
> .tneilc eht ma I

Be careful it's just a sample code for test send and receive data, And it is not useful for executive work.

I suggest you use these projects:

And also I suggest you these articles for more details:

Sockets with PHP and Node :: Code In PHP, I described my idea for connecting PHP and Node.js for real-time communication at and manipulations in PHP; We will create a web socket server in Node. (​So, we can send any message to the client anytime from Node. Here are the steps you need to take in fixing the Can't connect to local MySQL server through socket error message generated by MySQ>

I'm not aware of anything that provides arbitrary socket capabilities for JS. There is limited support for Web Sockets (which I think will require you to modify the server to conform to the space). Failing that, simple XHR might meet your needs (which would require that you modify the server to act as a web service). If the service runs on a different origin to the page, then you will need to use CORS or use a work around such as JSONP.

Creating a Real-Time Chat App with PHP and Node.js, In this chat example, we use sockets to communicate with the server. For establishing a socket connection between the client and the server, we  I'm trying to connect a PHP-based client to a websocket server. Here's the code I have been using which has been widely published on different forums. But for some reason I just cannot get it to work. Any help would be appreciated.

Try this:

Simple PHP Chat using WebSocket, Learn how to build a PHP WebSocket server to build real-time, event-driven can decide what to do based on which client is connected. In our  server.php: Creates the WebSocket server instance, sets server properties, and registers the application to be called by the client component. SplClassLoader.php: Implements the technical interoperability standards for PHP 5.3 namespaces and class names. Connection.php: Manages the WebSocket Connection.

How to Create a WebSocket Server in PHP with Ratchet for Real , We host a WebSocket Echo Server at ws:// which additionally Once connected, enter a message and press the Send button. <​meta charset="utf-8" /> <title>WebSocket Test</title> <script language="javascript​"  Is there a way that a javascript running in a browser can connect to a tcp socket and send some data and listen on it for some more data response on the socket and print it to the browser. If this is possible can some one point me in the right direction as to which would help me establish the goal. Echo Test, With this API, you can send messages to a server and receive and EventSource (one-way connections) for Node.js Server and Client. Here unlike server, client socket is not bound with port and host. Instead it connects to server socket, waiting to accept the connection from client socket. Connection of client socket to server socket is established in this step.

The WebSocket API (WebSockets), Now you can use a library like laravel-echo to connect to the server. When executing php artisan websockets:serve you'll notice that the purpose is to make the usage of either the Pusher Javascript client or Laravel Echo  The client(s) must connect to a webpage (in PHP) Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send.

  • Javascript is a client side scripting and it doesn't provide opening socket afaik. I don't think it's possible at the point of writing.
  • What JS environment are you running in? Node? WSH? ASP? A browser plugin? A browser viewing a webpage? Something else?
  • @Lionel Chan — JS is a generic programming language and doesn't provide a whole lot of I/O period — that comes from the host environment.
  • @Quentin yep, I have +1 your comment because I forgot thing like Node.JS :) - more of a misread the question
  • @quentin Browser viewing a web page