Store Binary Data in String Using PHP

Introduction

We are describing how to store binary data in strings with the use of functions using two core functions in PHP. We want to parse a string containing encoded binary values. We will see an example of storing numbers of the binary representation instead of sequences of ASCII characters so you need to use the pack() function to store the binary data in a string.

Pack(): Pack data into a binary string.

Unpack(): Unpack data from a binary string.

$pack_data = pack('S3',1994,54,225);

 

The first argument of the pack() function is the format as a string that shows how to encode the data and other arguments of the data we want to pack as a binary string. The s3 format produces the three unsigned short 16-bit numbers in byte order from its input data. Given the input "1994,54,225" it returns eight bytes.

Now, let's see the "unpack()" function. It unpacks from a binary string into an array depending on the specified format. The unpacked data is stored in an associative array.

 

Syntax

 

$return = unpack('S3',$pack_data);
print_r($return);

The first argument of the unpack() function is also a format as a string and the second argument is the encoded data that you want to decode and the output of the unpack() function will be the decoded data as an associative array.

<?php

$pack_data = pack('S3',1994,54,225);

$return = unpack('S3',$pack_data);

echo "<pre>";print_r($return);

?>

Output

Pack-Unpack-function-in php.jpg

Example

<?php

$pack_data = pack('S3',1994,54,225);

$return = unpack('S3no',$pack_data);

echo "<pre>";print_r($return);

?>

Output

Pack-Unpack-function-in php1.jpg

Example

<?php

$pack_data = pack('S3',1994,54,225);

$return = unpack('S1a/S1b/S1c',$pack_data);

echo "<pre>"; print_r($return);

?>

Output

Pack-Unpack-function-in php2.jpg

There are many format characters that can be used with the "pack( )" and "unpack( )" functions.

Up Next
    Ebook Download
    View all
    Learn
    View all