Different PHP results between base64_encode and convert.base64-encode

Viewed 1015

In PHP, it exists two ways to encode content in base64. We can use function base64_encode which takes a string or use the string filter convert.base64-encode to use with a stream. But I can't produce the same result with these two methods.

<?php

$content = "foo";

$encoded1 = base64_encode($content);

$stream = tmpfile();

stream_filter_append($stream, 'convert.base64-encode');

fwrite($stream, $content);
fseek($stream, 0);

$encoded2 = stream_get_contents($stream);

echo sprintf(
    "Content encoded with base64_encode(): %s\nContent encoded with convert.base64-encode filter: %s\n",
    $encoded1,
    $encoded2,
);

Output

Content encoded with base64_encode(): Zm9v
Content encoded with convert.base64-encode filter: Wm05dg==

In the documentation, this citation can be read.

Use of these filters are equivalent to processing all stream data through the base64_encode() and base64_decode() functions respectively.

1 Answers

This is because the stream filter appends itself in read/write mode, so reading the file again without closing the handle would apply base64 one more time; in your case, you only want the filter to apply when writing.

A simple fix:

stream_filter_append($fp, "convert.base64-encode", STREAM_FILTER_WRITE);

This is also discussed in one of the examples of the manual.

Related