Search code examples
phpbase64decodeencode

base64_decode adding strange characters


I'm using base64_encode to use on a return URL string, but when I get to the page to decode it (using base64_decode) it's adding this to the end of the string:

-zh��

Here's the code which encodes the string:

$sess_refer = 'http://www.mysite.com/create-report.html?view=report&layout=reports&data=selection'

<input type="text" name="referrer" id="referrer" value="<?php echo base64_encode($sess_refer); ?>" />

Here's the code which decodes the string:

$referrer = JRequest::getVar('referrer');
$sess_refer = base64_decode($referrer);

Which outputs this:

http://www.mysite.com/create-report.html?view=report&layout=reports&data=selection-zh��

Any idea on what I'm doing wrong?


Solution

  • This was a bit too long for a comment, but if it doesn't help I'll remove this answer.

    You can make base64_encode() data web-safe by applying the below trick. Without it, the + gets turned into a space and might mess up the encoding.

    strtr(base64_encode($s), '+/', '-_');
    

    To decode:

    base64_decode(strtr($s, '-_', '+/'));
    

    Update

    Also, the HTTP_REFERER is sent by the browser, so it should be treated as user input and thus should be sanitized as a valid URL, before you base64_encode() it.