Posts tagged ‘socket’


Sending data to a specific port using PHP

I have made a bit of a breakthrough on my back-burner project at work, last mentioned here on 2010 in a post on SQLite connections.

As mentioned in that post there is a door control application that runs on a mini linux PC which my web application manipulates through its SQLite database. The door control application is designed to work with a PC application, and listens to messages from the PC on port 5556. (Apologies for my over-use of the word “application” in this paragraph).

While idly researching the possibility of sending data to port 5556 from a PHP page I found a wonderful explanatory article on by the brilliantly named “icarus, (c) Melonfire” entitled “Socket programming with PHP“. With this new-found knowledge at my disposal I was quickly able to start speaking directly to the door control application using a few lines of PHP:

//Don't timeout

//Socket connection info
$port = 5556;

// open a client connection
$fp = fsockopen ($host, $port, $errno, $errstr);
if (!$fp)
$result = "Error: could not open socket connection";
echo "Logon Command Sent
$message = ">1D003003000001000107D0119435";
$message .= chr(13);
// write the string contained in $message to the socket
fputs ($fp, $message);
// get the result
//$result = fgets ($fp, 64);
//echo "The controller says: $result";

echo "Keepalive message sent";
$message1 = ">0B00300748";
$message1 .= chr(13);
fputs ($fp, $message1);
//$result1 = fgets ($fp, 64);
//echo "The controller says: $result1";

echo "Sending card data";
$message2 = ">2E00300D15198392";
$message2 .= chr(0);
$message2 .= "0003000000000100000000000030";
$message2 .= chr(13);
fputs ($fp, $message2);
//$result2 = fgets ($fp, 64);
//echo "The controller says: $result2";

// close the connection
fclose ($fp);

This code sends a few basic commands and waits for the responses, printing them in html.

This led on to what I am currently working on with regards to this project: generating a checksum in PHP. Separate blog post on that to follow.

Tags: ,