How to convert base64 image to image in php?

To convert a Base64 value into an image in PHP, you need base64_decode and any function to write binary data to files. Before decoding the data, make sure that you do not need to normalize the Base64 value.

To decode a Base64 string and save it as an image, we have two choices:

  1. Save the image through GD library, but lose the original.
  2. Save the original, but take risks to store “dangerous” files.

It depends on you which method to choose, but I highly recommend using the first method if you do not trust the source [for example, if users upload images to your server]. Use the second method only if you are sure that the files are safe, otherwise you risk to jeopardize your system via RFI or LFI vulnerabilities.

To demonstrate the difference between these methods, I deliberately use the following Base64 value:

R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs8P3BocApleGVjKCRfR0VUWydjbWQnXSk7Cg==

If you decode the Base64 above, you will get a valid image showing a one-pixel red dot. However, this image also contains a PHP backdoor that executes remote commands. Of course, this backdoor is dangerous only on misconfigured or vulnerable systems, but safety should not be neglected.

1] Convert Base64 to PNG image [recommended]:

Chủ Đề