John Smith
John Smith

Reputation: 387

Converting PHP strings to binary format and reconverting them when connecting to server

I'm looking to code a php script that would connect to a server using binary protocol, send queries and receive data from it. I wondered how I can implement this in php? So far I have:

<?php
$fp = fsockopen("111.111.10.10", "2222", $errno, $errstr, 10);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
    fwrite($fp, "You message");
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
?>

When I speak of binary, I don't mean the underlying of computer language, I mean that the specific string that is sent to the server should be converted in "0101001", since that is the way server reads and converts info. I need a way to convert php strings to this format and reconvert them back.

I will explain if you don't fully understand the question.

Upvotes: 2

Views: 8132

Answers (3)

Hugo Delsing
Hugo Delsing

Reputation: 14173

To create a binary string from a string, you need a few steps.

First change all characters to numeric with ord() and then convert the number from decimal to binary with decbin.

Then I used str_pad to make it have 8bits per charactor.

I added a spacer for readability

<?php
$str = 'Hello world';
$l = strlen($str);
$result = '';
while ($l--) {
    $result = str_pad(decbin(ord($str[$l])), 8, "0", STR_PAD_LEFT) . ' - ' . $result;
}
print $result;

//01001000 - 01100101 - 01101100 - 01101100 - 01101111 - 00100000 - 01110111 - 01101111 - 01110010 - 01101100 - 01100100
?>

This works for simple ASCII characters, but most encodings, like UTF8, can use multiple bytes per char. (variable length)

Simply padding to 8 bits won't work.

Upvotes: 4

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

use pack and unpack to convert to/from binary

Upvotes: 1

Mihai Stancu
Mihai Stancu

Reputation: 16107

They already are in a binary representation. Transmitting them to the server via fwrite should be enough.

The other end of the socket will receive the binary string and process it as is.

Upvotes: 0

Related Questions