Reading binary data from a file

This can be potentially dangerous since the exact format for the binary data can differ depending on convention and system. The advantage is that it usually gives smaller data files and is usually not as suspect to data corruption since it is not easy to read directly into a text editor and change. In PHP a variable can be stored in a binary format using the serialize() function and read back from a file with unserialize()


It is also possible to store binary data in a text file as a string. One way of doing this is to do a base64 encoding of the binary data. This will guarantee that the encoded data will only be printable characters which can be stored in a normal string. One thing to remember is that this will enlarge the data by roughly 30%. Another example on when base64 encoding is useful is to store binary images in a text file. This is the way for example all built-in images are stored in the library. The image is the re-created from the string by first decoding the base64 data and then read in the data with the GD function imagecreatefromstring() .