Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I send the binary representation through a PHP socket?

I'm trying to send the binary representation of data through a PHP socket.

So if the number was 15, socket_write would send 00001111 as binary representation for 15.

How should I do this?

like image 475
Mitchell M Avatar asked Mar 25 '26 07:03

Mitchell M


2 Answers

Use the chr function:

socket_write( $fp, chr(15));

You can also use \x escapes with hex values:

socket_write( $fp, "\xff\xff\xff\xff" );

Would send 4 bytes, with values 255 on each.

like image 56
Esailija Avatar answered Mar 26 '26 22:03

Esailija


To generate a binary representation from arbitrary data use the pack() function.

Example:

$data = pack("v", 15); // "i" is unsigned little endian integer
socket_write($socket, $data);

See the manual page for more information on the various formats. There's also unpack() for the reverse functionality.

like image 32
Koraktor Avatar answered Mar 26 '26 21:03

Koraktor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!