Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


reading and writing binary files

Posted on 2005-03-15
Medium Priority
Last Modified: 2008-03-06
How can I create a binary file using PHP

ie I want to store say these information

1 bytes (record number)
10 bytes (name)

so say i have a record number that is represented by a byte followed by a name that is made up of 10bytes.

How would I create a binary file with this information? Seem like even though I use the"b" mode when openning files the record number gets stored as a string instead of a byte.

I can't use a text file for what I am trying to do.

Question by:rukiman
1 Comment
LVL 17

Accepted Solution

davebytes earned 375 total points
ID: 13552654
first, you need to convert data to binary format.  if the record number is supposed to be a number, you need to write out the byte format of the integer (i.e., intval($recordnum)) rather than writing just a string.  Read the following page:

Has a LOT on various file i/o stuff.  Eventually you'll reach the pack(), unpack() functions, helpful if you are writing complex data structures in binary.

second, use fwrite($file, $data, $datalength) variation -- ALWAYS specify the data length writing binary data, otherwise PHP may 'transform' things under the hood.  don't use the string file functions, fgets, fputs, even though they may be aliased.  Stick with fread/fwrite.

That make more sense?

Also, you can use serialize($datastructure) to convert complex arrays and variables into a format suitable for writing into an ascii text file, and read it back with unserialize($data).  Just fyi.


Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question