0

I need to decode a base64 encoded string.

I need to do it with PHP.

The base64_decode() does not do the job.

I tried with:

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

...it only works sometimes.

The same happens with:

base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));

I really do not know how to approach this.

UPDATE:

The data comes from an attached file via GMAIL API.

I save it into the DB, utf8mb4 TEXT field.

I do mysqli -> real_escape_string() before inserting.

Then I extract it from the DB as $data.

Álvaro N. Franz
  • 1,188
  • 3
  • 17
  • 39
  • If it doesn't work with `base64_decode()` then it probably isn't a base64 encoded string. It might have been corrupted going through the pipe. Can you give an example and your expected output? – ishegg Sep 20 '17 at 14:41
  • @ishegg I updated the question with more info. – Álvaro N. Franz Sep 20 '17 at 14:51
  • I see. Is it not possible for you to provide an example of the bas64 encoded string? Otherwise it's a harder to help you in the dark. – ishegg Sep 20 '17 at 14:53
  • 1
    [In the docs](https://developers.google.com/gmail/api/v1/reference/users/messages/attachments) it says `a base64url encoded`, so if you can see `%3D` in the string, you only need to do `$attch = base64_decode(urldecode($in))` and thats it. – Lawrence Cherone Sep 20 '17 at 14:57
  • @LawrenceCherone Thanks, I tried that one too. But it did not work neither. (Also, there are no `%3D` in the string) – Álvaro N. Franz Sep 20 '17 at 15:15

1 Answers1

0

Not sure if this is still needed, but I had a base64 encoded string that itself was url encoded HTML. So the answer for me was to urldecode() AFTER doing base64_decode().

This means wrapping the functions backwards:

$html = urldecode(base64_decode($data))