[英]PHP - Pack array with binary data
有一個服務(php),可將圖像發送到客戶端(php)。
header('Content-Type: image/png');
readfile($image);
如果不僅需要發送圖像,還需要發送一些數據,該怎么辦。
$arrayToSend = [
'image' => file_get_contents($image),
'some_data' => [
'a' => 1,
'b' => 2
]
];
服務如何打包$ arrayToSend,以便客戶端可以對其進行打包?
無需將圖像轉換為base64(因為尺寸太大)。
也許您可以將some_data-a
和some_data-b
作為標頭傳遞? 例如,作為cookie。
您可以通過以下文檔來幫助自己: https : //developer.mozilla.org/pl/docs/Web/HTTP/Headers ,以獲取有關標頭的更多信息。
@Danon的標頭方法可能是通過HTTP進行通信的方法,但是其他傳輸可能不支持發送其他標頭,因此您需要將它們與二進制數據打包在一起,然后在接收端進行拆包。
<?php
class Codec
{
/**
* Pack metadata along with binary data
*
* @param $meta
* @param $data
* @return false|string
*/
public static function encode($meta, $data)
{
$meta = base64_encode($meta);
//determine length of metadata
$metaLength = strlen($meta);
//The first part of the message is the metadata length
$output = pack('VA*', $metaLength, $meta);
//Length and metadata are set, now include the binary data
$output .= $data;
return $output;
}
/**
* Unpack data encoded via the encode function.
* Returns an array with "meta" and "data" elaments
*
* @param $content
* @return array
*/
public static function decode($content)
{
//Get the length of the metadata content
$metaLength = unpack('V', $content)[1];
//Slice out the metatdata, offset 4 to account for the length bytes
$metaPacked = substr($content, 4, $metaLength);
//Unpack and base64 decode the metadata
$meta = unpack('A*', $metaPacked)[1];
$meta = base64_decode($meta);
//The binary data is everything after the metadata
$data = substr($content, $metaLength+4);
return [
'meta' => $meta,
'data' => $data
];
}
}
//Load contents of a binary file
$imageFilePath = 'path_to_image.png';
$data = file_get_contents($imageFilePath);
//Arbitrary metadata - could be anything, let's use JSON
$meta = [
'filename' => 'foo.png',
'uid' => 12345,
'md5' => md5_file($imageFilePath)
];
$metaJson = json_encode($meta);
//Encode the message, you can then send this to the receiver
$payload = Codec::encode($metaJson, $data);
//Receiver decodes the message
$result = Codec::decode($payload);
//Decode our JSON string
$resultMeta = json_decode($result['meta'], true);
echo 'Filename: '.$resultMeta['filename'].PHP_EOL;
echo 'UID: '.$resultMeta['uid'].PHP_EOL;
//We included an MD5 hash of the file, so we can verify here
if($resultMeta['md5'] != md5($result['data']))
{
echo 'MD5 mismatch!';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.