• 0

[C# Help] PHP Compatible String GZip


Question

Firstly I'm not a real application developer, I primarily work on the web-side of things and most of the issues I'm dealing with are things I've never looked at before so I'm at a loss as to a solution for my current problem.

But I'm currently working on a small desktop application that periodically uploads a string to a website every 20-30 seconds, to reduce the time it takes and to reduce any latency issues I'm looking to gzip the string before sending it to a php script. I've gotten a few examples of the compression function on the C# side of things and plenty examples of gzip (de)compression in PHP, but after hours of looking I haven't found a way to get it to work with PHPs gzinflate(), gzdecode() or gzuncompress(). I was wondering if anyone has managed to get this type of marriage to work before?

The current c# compression function I'm using:

        public static string Compress(string text)
        {

            byte[] buffer = Encoding.UTF8.GetBytes(text);
            MemoryStream ms = new MemoryStream();
            using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
            {
                zip.Write(buffer, 0, buffer.Length);
            }

            ms.Position = 0;
            MemoryStream outStream = new MemoryStream();

            byte[] compressed = new byte[ms.Length];
            ms.Read(compressed, 0, compressed.Length);

            byte[] gzBuffer = new byte[compressed.Length + 4];
            System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
            System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);

            return Convert.ToBase64String(gzBuffer);
        }

Example output from the function that is sent to the PHP script via post: http://www.recount.me/gzip.txt

Which I am then trying to use any of the following functions to decode:

	echo gzinflate(base64_decode($str));
	echo '<br /><br />';
	echo gzdecode(base64_decode($str));
	echo '<br /><br />';
	echo gzuncompress(base64_decode($str));

After looking around I think the issue lies with the fact that many of the PHP functions are designed with files and because I'm using a string it has no header/footer data that it expects to see, but having never really worked with c# or gzip I have no idea how to fix the problem and any advice/help would be very much appreciated.

Thanks for reading.

Link to comment
https://www.neowin.net/forum/topic/994146-c-help-php-compatible-string-gzip/
Share on other sites

2 answers to this question

Recommended Posts

  • 0

Well, that block of C# code adds a 4-byte length to the beginning of the gzip-encoded data, which by definition includes a header and a CRC/length trailer. So of course the PHP functions won't recognize it. Cut out all of that BlockCopy crap.

Not tested, but maybe something like this:

public static string Compress(string text)
{
    byte[] buffer = Encoding.UTF8.GetBytes(text);
    string output = String.Empty;

    using (MemoryStream ms = new MemoryStream())
    {
        using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)
        {
            zip.Write(buffer, 0, buffer.Length);
        }

        output = Convert.ToBase64String(ms.ToArray());
    }

    return output;
}

  • 0

Thank you so much for the quick reply and even more so for a working solution...I can't believe it was that simple in the end!

I ripped out the useless parts like you suggested rather than using your code and it work perfectly. So the final solution I'm using is:

        public static string Compress(string text)
        {

            byte[] buffer = Encoding.UTF8.GetBytes(text);

            var memoryStream = new MemoryStream();
            using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress, true))
            {
                gZipStream.Write(buffer, 0, buffer.Length);
            }

            memoryStream.Position = 0;

            var compressedData = new byte[memoryStream.Length];
            memoryStream.Read(compressedData, 0, compressedData.Length);

            return Convert.ToBase64String(compressedData);
        }

And for the php side:

<?php

	$str = trim($_REQUEST['data']);
	echo gzdecode(base64_decode($str));

?>

And it's taking 70KB strings down to 10KB without any loss of data which is exactly what I was looking for.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I can name 10x that on why not to switch.... It's funny outlook/office are going towards web app wrappers, and then MS is now preaching native apps again.... ugh can we just pick a lane and stay in it
    • Absolutely NOBODY has suggested such a conclusion. I am affirming the sober reality check that AV2's overall market adoption will take longer than AV1's adoption rate -- which, by the way, is the whole point of the article! While PCI-SIG is productive (on paper), other WGs have created all sorts of confusing progress plans that consumers have tuned-out of their improvements... HTML/W3C, USB, HDMI, BT, WIFI (ieee802.11) as a few other groups where spec naming conventions, split progress paths, overlapping ambitions... I'm not critiquing the AV specs group; I'm simply affirming that adoption for AV2 faces headwinds beyond the macroeconomics of it all.
    • Segra 1.5.2 by Razvan Serea Segra is a free, open-source OBS-powered game recorder offering fast gameplay capture, instant clips, AI highlights, deep game integration, and seamless uploads—perfect for gamers, streamers, and content creators. Lightweight, fast, zero bloat. Segra key features: Automatic Game Recording: Begin capturing gameplay the moment your game launches, with zero manual setup. Instant Clipping: Save important moments instantly using a customizable hotkey—perfect for highlights, montages, or quick shares. Segra AI Highlights: Let Segra automatically detect kills, assists, deaths, and key events to generate polished highlight reels without manual editing. Gameplay Uploads: Upload recordings and clips directly to Segra.tv for fast sharing and cloud access. Deep Game Integration: Enjoy advanced game-data tracking across hundreds of supported titles, enabling smart highlight generation and stat-informed clipping. High-Performance Capture: Record up to 4K at 144 FPS using OBS-powered technology with minimal performance impact, supporting NVENC, AMD VCE, and custom quality controls. Segra Editor: Edit recordings easily with timeline controls, segment management, and event-based navigation to build the perfect clip. Customization Options: Adjust hotkeys, output formats, storage paths, codecs, capture quality, and performance settings for a tailored recording experience. Segra 1.5.2 changelog: Settings: Added an Airplane Mode that hides account, login, and upload features. Storage: Added a button to migrate videos into the recording path after changing it. Import: Added auto-scroll and a highlight pulse to videos right after importing. Recording: Added graceful handling of low disk space and output failures, finalizing files safely with clear errors. Recording: Added a guard blocking recording when any drive exceeds 99% full. OBS: Removed the download timeout to support users with slow internet. Clips: Fixed an error modal incorrectly appearing when clip creation was cancelled. Settings: Fixed the content folder path not refreshing in the UI after changes. Updates: Improved error handling for multiple simultaneous update checks. Stability: Fixed a WebSocket reconnect loop that ran while the window was backgrounded. Dependencies: Updated project dependencies. Maintenance: Removed dead code, reduced duplication, and fixed several latent bugs. Download: Segra 1.5.2 | 73.1 MB (Open Source) View: Segra Homepage | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Very Popular
      s0nic69 earned a badge
      Very Popular
    • Collaborator
      Asgardi earned a badge
      Collaborator
    • Conversation Starter
      mobandz earned a badge
      Conversation Starter
    • Apprentice
      fernan99 went up a rank
      Apprentice
    • One Month Later
      nothanks earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      472
    2. 2
      PsYcHoKiLLa
      246
    3. 3
      Skyfrog
      79
    4. 4
      FloatingFatMan
      69
    5. 5
      Michael Scrip
      60
  • Tell a friend

    Love Neowin? Tell a friend!