Back to Top

How To Store Binary Data in PHP

Here is one more quick article about to store binary data in strings with the use of two core functions in PHP.

Like, You want to parse a string that have values encoded as a binary structure or want to encode values into a string.Let’s see an example that you want to store numbers in the binary representation instead of sequences of ASCII you need to use the pack() function to store binary data in a string.

What is pack() method?

pack() method is mainly used to store the data in binary form in PHP

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

What is unpack() function?

unpack() transforms binary data into an associative array based on the format.


Here, Format parameter is used when unpacking and binary_string is used to unpack Binary string.This function parses a binary string according to a user-defined format.


It returns an associative array and FALSE on error.

Now, Let’s see unpack() function

unpack() function SYNTAX

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


You can use different format characters and their count can be followed by an array key in unpack() function.



Even you can use multiple formats and can separate them by a slash / with unpack() function.You can also use unpack( ) as a substitute for substr( ) method to extract fields.Both substr( ) and unpack( ) function have equivalent capabilities when the fixed-width fields but unpack( ) is the better solution when the elements of the fields aren’t just strings.



There are many format characters that can be used with the pack( ) and unpack( ) function. you can see format character in PHP Manual. Do you have any question about pack() and unpack() function? Let me know in comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to display ADMIN Toolbar in UI

Posted on 7 years ago


How to change Base Path in Typo3

Posted on 6 years ago


How to allow more MIME types in WordPress

Posted on 5 years ago