Blog / Home
About
Media Gallery

Welcome
to
Thronic.com

ժʝ_

Base64 GZipStreamed JSON to PHP


Small note on how I gzipped some JSON and then base64 string-coded it for posting to a PHP script. This can save a lot of bandwidth over time when using automated submittals of data with short intervals. The JSON (FinalOutput) below was created beforehand using JsonConvert.SerializeObject (Newtonsoft.Json).

C# Payload
// Prepare POST data.
PostData = "AgentToken="+ AgentToken +"&PackageDelivery=";
JSONBytes = Encoding.UTF8.GetBytes(FinalOutput);
using (MemoryStream ms = new MemoryStream()) {
	using (GZipStream gzs = new GZipStream(ms, CompressionMode.Compress)) {
		gzs.Write(JSONBytes, 0, JSONBytes.Length);
	}
	PostData += Convert.ToBase64String(ms.ToArray());
}
PostDataBytes = Encoding.UTF8.GetBytes(PostData);

// Send to online service.
// ~25kB zipped down to ~3kB every 4 second.

PHP Receiving
// Unwrap Base64 and uncompress the JSON data.
$PackageDelivery = str_replace(" ", "+", $_POST["PackageDelivery"]);
$JSON_raw = gzdecode(base64_decode($PackageDelivery));
$JSON_decoded = json_decode($JSON_raw, true);



Original Post: Jan 27th, '22 19:32 CET.
Updated: Jan 27th, '22 19:33 CET.

PHP C#
π