file - Saving hex data in binary using PHP does not work properly -
i learning php , files , trying write code put data in binary file.
here's code:
write
<?php echo "\n\nwrite: \n\n"; $c = array(); $data = ''; $c['name'] = 'abcdefghijklmnopqrstuvwxyz'; $data .= implode('', $c); $fp = fopen('test.bin', 'wb'); $len = strlen($data); echo "\nfile content: $data (strlen: $len)\n\n"; ($i = 0; $i < $len; ++$i) { $hx = dechex(ord($data{$i})); fwrite($fp, pack("c", $hx)); } echo "last char is: $hx mean: "; echo chr(hexdec('7a')); echo "\n--------------------------------------------\n"; fclose($fp);
output
file content: abcdefghijklmnopqrstuvwxyz (strlen: 26) last char is: 7a mean: z
read
<?php echo "\n--------------------------------------------\n"; echo "\n\nread: \n\n"; $fp = fopen('test.bin', 'rb'); $fseek = fseek($fp, 0, seek_set); if($fseek == -1) { return false; } $data = fread($fp, 26); $arr = unpack("c*", $data); $return = ''; foreach($arr $val) { $return .= chr(hexdec($val)); } $n = ''; $arr = array(); $arr['name'] = substr($return, 0, 26); print_r($arr); echo "\n--------------------------------------------\n";
output
array ( [name] => abcdefghipqrstuvwxy )
where missing letters z
, m
, n
or o
?
edit 6-3-14 7h36 am: have .bin file not plain text if possible
you trying set hex chars in char (c - unsigned char) instruction.
echo "\t"; foreach( array('0x41', 65, 'a') $o ) echo $o."\t"; echo "\n"; foreach( array('c*','c*','a*','a*','h*','h*','v*','n*','s*') $o ){ echo $o . "\t"; foreach( array(0x41, 65, "a") $oo ) { echo pack($o, $oo); echo "\t"; } echo "\n"; }
if run this, see how pack works 3 different values of (hex, dec , normal).
you have use h
instruction accomplish need.
function writetofile($data) { $fp = fopen(filename, 'wb'); $len = strlen($data); ($i = 0; $i < $len; ++$i) { $hx = dechex(ord($data[$i])); $result = fwrite($fp, pack("h*", $hx)); if(!$result) { // show } } fclose($fp); }
now, read data. need use same 1 h
and split string (split using str_split parameter 2 since it's hex 00 = 0 , ff = 255 - assuming won't go on 255). since h
returns array single element. once string back, need convert number ord
in writetofile
using chr
function.
function readfromfile($lenght, $pos = 0) { $return = ''; $fp = fopen(filename, 'rb'); if(!$fp) { // show } $fseek = fseek($fp, $pos, seek_set); if($fseek == -1) { // show } $data = fread($fp, $lenght); $data = unpack("h*", $data); $arr = str_split(current($data), 2); foreach($arr $val) { $return .= chr(hexdec($val)); } return $return; }
now, create string , write file:
$data = 'this should work properly, stackoverflow!'; $len = strlen($data); writetofile($data);
then read back:
echo readfromfile($len);
the content of file this:
e<86><96>7^b7<86>öwÆf^bwö'¶^b^g'ö^gv'Æ<97>Â^bg<86>^væ¶7^bfö'^b5g^v6¶ôgv'dÆöw^r
Comments
Post a Comment