PatlaDJ
PatlaDJ

Reputation: 1249

How to write byte by byte to socket in PHP?

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.

Upvotes: 5

Views: 11653

Answers (3)

Mark Tomlin
Mark Tomlin

Reputation: 8933

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);

Upvotes: 7

Earlz
Earlz

Reputation: 63835

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);

Upvotes: 1

Kevin Vaughan
Kevin Vaughan

Reputation: 15180

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.

Upvotes: 0

Related Questions