1

I wish to produce a gzip'ed STRING in bash, and then send it to a php script for decoding/inflating. But I am coming across a problem with, I think, the gzip'ed string produced by gzip in bash.

    # from 
    # https://stackoverflow.com/questions/7538846/un-decompress-a-string-in-bash#7539075
    FOO="$(echo "Hello world" | gzip -c | base64)" # compressed, base64 encoded data
    echo $FOO | base64 -d | gunzip # use base64 decoded, uncompressed data
    echo '--'

    # unpack base64 again before sending to php
    FOO="$(echo $FOO | base64 -d)"

    # this is where it goes wrong:
    # php doesn't seem to like the gzip string format.

    # gzuncompress produces:
    #   PHP Warning:  gzuncompress(): data error in Command line code on line 1
    php -r "echo gzuncompress('$FOO') . \"\n\";"
    echo '--'

    # gzdecode produces:
    #   PHP Warning:  gzdecode(): data error in Command line code on line 1
    php -r "echo gzdecode('$FOO') . \"\n\";"
    echo '--'

    # gzinflate produces:
    #   PHP Warning:  gzinflate(): data error in Command line code on line 1
    php -r "echo gzinflate('$FOO') . \"\n\";"
    echo '--'

I am suspecting that the problem may be with the bash gzip format.
But I am unable to see any options that might correct this.

All thoughts appreciated.

Gary Dean
  • 23
  • 9

1 Answers1

2

The gzipped string is not safe in a bash string, if i run

FOO="$(echo "Hello world" | gzip -c | base64)"
FOO="$(echo "$FOO" | base64 -d)"

I get an error

-bash: warning: command substitution: ignored null byte in input

But it works if I leave the string base64 encoded like this using base64_decode() / gzdecode():

FOO="$(echo "Hello world" | gzip -c | base64)"
php -r "echo gzdecode(base64_decode('$FOO'));"

Output:

Hello world

It also works if you pipe the output of the decoded string to PHP:

FOO="$(echo "Hello world" | gzip -c | base64)"
echo "$FOO" | base64 -d | php -r 'echo gzdecode(file_get_contents("php://stdin"));'

(example to read from stdin taken from here)

Freddy
  • 4,548
  • 1
  • 7
  • 17