Search code examples
phpencodingbase64

what are the differences between PHP base64_encode and *nix base64


PHP's base64_encode is returning a different string to the linux base64 command. Why is this?

PHP:

$ php
<?php
echo base64_encode('test');
?>
dGVzdA==

Linux base64:

$ echo 'test' | base64
dGVzdAo=

Solution

  • echo usually outputs a new line character at the end of the string, to suppress that use the -n switch:

    $ echo -n 'test' | base64
    dGVzdA==
    

    Or even better, use the portable printf:

    $ printf 'test' | base64
    dGVzdA==
    

    Similarly for PHP:

    $ php <<PHP
    <?php echo base64_encode("test\n"); ?>
    PHP
    dGVzdAo=