views:

351

answers:

3

How to write byte by byte to socket in PHP?

For example how can I do something like:

socket_write($socket,$msg.14.56.255.11.7.89.152,strlen($msg)+7);

The pseudo code concatenated digits are actually bytes in dec. Hope you understand me.

A: 

Before PHP 6, bytes are just characters. Writing a string out is the same thing as writing an array of bytes. If those are the ascii character decimal values, you can replace your $msg... bit with:

$msg.chr(14).chr(56).chr(255).chr(11).chr(7).chr(89).chr(152)

If you could explain what you are attempting to do it will be easier for us to provide a more helpful answer, but in the meantime that accomplishes what you've described so far.

Kevin
Is it safe enough ?
PatlaDJ
Not with PHP 6 apparently..
Earlz
What do you mean by safe? PHP 6 introduces unicode which means it will no longer be 1 byte = 1 character. The parameters and returns of (some) various string functions will change, and your code will have to be updated accordingly. The online documentation for the functions describe those changes.
Kevin
Yes you are right.I agree. Going utf8 shouldn't be affected by byte->char conversion as long as we are able to read it also as bytes on the other side of the socket. But how exactly will be the 'byte safe' way to split utf8 string back into bytes? They will add function subbyte :) That would allow us to iterate thru bytes instead of characters or what? :)
PatlaDJ
A: 

As per http://www.php.net/manual/en/function.socket-create.php#90573

You should be able to do

socket_write($socket,"$msg\x14\x56\x255\x11\x7\x89\x152",strlen($msg)+7);
Earlz
The values in the questions are "bytes in dec" (decimal). The \x### format are hexidecimal values, so this will give the wrong result.
Kevin
Thank you Kevin and Earlz.Do you think this solution will be PHP6 safe? I can see now they are finally moving above simple ascii strings.
PatlaDJ
So just convert the decimal values to hex. Most things are more readable in hex anyway
Earlz
According to http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double you can't insert raw values except for in hex or octal, so take your choice.
Earlz
+1  A: 

You can use the pack function to pack the data into any datatype you wish. Then send it with any of the socket functions.

$strLen = strlen($msg);

$packet = pack("a{$strLen}C7", $msg, 14, 56, 255, 11, 7, 89, 152);

$pckLen = strlen($packet);

socket_write($socket, $packet, $pckLen);
Mark Tomlin
Who is down voting everyones answer? That is really very poor form.
Mark Tomlin
Thank you Mark.This function was unfamiliar to me.It was very helpful solution. And looks like it is safe - having the unpack function on the other side :)
PatlaDJ
Pack feels like a hidden function to me, but once you find it, it's a gem.
Mark Tomlin