If you want write something strange, like string array to binary string, and you are afraid 0-days of php's serialize function, you can use this.
Out:
string(88) "031a000a0001004c6f72..."
array(3) {
[0]=>
string(26) "Lorem ipsum dolor sit amet"
[1]=>
string(10) "8726348723"
[2]=>
string(1) "1"
}
string(152) "1c5e108afdec7c27a..."
array(3) {
[0]=>
string(26) "Lorem ipsum dolor sit amet"
[1]=>
string(10) "8726348723"
[2]=>
string(1) "1"
}
<?php
$arrToPack = array('Lorem ipsum dolor sit amet', 8726348723, true);
$packer = new ArraysPack();
$packer->privateKey = hash('sha256', 'k6LYiB8cnr5ESBMpVUBdC3c73Mt52p8w' ,true);
$dataPacked = $packer->pack($arrToPack);
$dataUnpacked = $packer->unPack($dataPacked);
$dataHMACPacked = $packer->hmacPack($arrToPack);
$dataHMACUnpacked = $packer->hmacUnPack($dataHMACPacked);
var_dump(bin2hex($dataPacked));
var_dump($dataUnpacked);
var_dump(bin2hex($dataHMACPacked));
var_dump($dataHMACUnpacked);
class ArraysPack
{
public $hmacAlgo = 'sha256';
public $hmacLen = 32;
public $privateKey = '';
public function hmacPack($array)
{
if(($ret = $this->pack($array)) === false)
return false;
$hmacHash = hash_hmac($this->hmacAlgo, $ret, $this->privateKey, true);
return $hmacHash.$ret;
}
public function hmacUnPack($binaryString)
{
if(strlen($binaryString) < $this->hmacLen)
return false;
$hmacHash = substr($binaryString, 0, $this->hmacLen);
$binaryString = substr($binaryString, $this->hmacLen);
$binaryStringHash = hash_hmac($this->hmacAlgo, $binaryString, $this->privateKey, true);
if(hash_equals($hmacHash, $binaryStringHash) === false)
return false;
return $this->unPack($binaryString);
}
public function pack($array)
{
if(!is_array($array))
return false;
$cnt = count($array);
$header = pack('C', $cnt);
$bin = '';
for($i=0;$i<$cnt;$i++) {
if(($strLen = strlen($array[$i])) > 65535 || $strLen === 0)
return false;
$header .= pack('S', $strLen);
$bin .= $array[$i];
}
return $header.$bin;
}
public function unPack($bin)
{
if(empty($bin))
return false;
$arr = array();
$cnt = unpack('C', $bin);
$cnt = $cnt[1];
if(!isset($bin[$cnt * 4]))
return false;
$header = substr($bin, 1, $cnt * 4);
$bin = substr($bin, ($cnt * 2)+1);
$int = unpack('S'.$cnt, $header);
for($i=1;$i<=$cnt;$i++) {
$val = substr($bin, 0, $int[$i]);
if($val === false)
return false;
$arr[] = $val;
$bin = substr($bin, $int[$i]);
}
if($bin !== false)
return false;
return $arr;
}
}
?>