Page 1 of 1

Read a file in hex/bin/dec format with PHP

Posted: Thu Apr 05, 2007 12:37 pm
by Oren
Is there some PHP function which I don't know which reads a file but returns it as hex/bin/dec and not as a string?

I'll clarify. Say I use this function to read a .gif image (which starts with "GIF" - like any valid .gif image) and I do:

Code: Select all

$data = this_secret_func_which_idk('my_image.gif'); // let's say it returns the data in hex format
echo $data{0}; // prints '47' since 'G' = 0x47
All I really want is a way to read file (from any type) byte by byte, or even bit after bit if possible.

P.S I'm working on something very cool and if I ever manage to finish it, a lot of PHP programmers will thank me 8)

Edit: I see this is my 1111 post :P

Posted: Thu Apr 05, 2007 1:20 pm
by stereofrog

Code: Select all

$bytes = file_get_contents(zzz);
$ints = unpack("c*", $bytes);
$hex = array_map('dechex', $ints);
echo $hex[0]; // 47
see pack, unpack, ord, chr, dechex, sprintf and others ;)

Posted: Thu Apr 05, 2007 1:37 pm
by Oren
Thanks man. I still need to test it and play with it, but it seems to be working.

P.S If you have other ways to do this I'm listening...

Edit: By the way... it needs to be: $hex[1] instead of: $hex[0]

Posted: Thu Apr 05, 2007 5:01 pm
by feyd
Why must it be a one-based array?

Posted: Thu Apr 05, 2007 5:59 pm
by Oren
I guess this is how unpack() works... I have no idea.

Posted: Thu Apr 05, 2007 6:06 pm
by feyd
I misread your post. I thought you were referring to a need in your program for a one-based array, not that unpack() was returning a one-based array.

Posted: Fri Apr 06, 2007 7:43 am
by Oren
Some of the elements in the result array are padded with f's (e.g a byte holds the value: 0xD0, it shows as: 'ffffffd0'). Why?

Thanks guys :P

Posted: Sat Apr 07, 2007 5:03 am
by Oren
C'mon guys... anyone? I'm working on something that may help a lot of people here 8)