Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

uniqueginun's avatar

convert base64 string to a valid file without knowing the file type

Hello

If I have a base64 string and I don't know if it is jpg or png or pdf or whatever, how do I convert it to a valid file?

0 likes
12 replies
Tray2's avatar

Why are you encoding it to base64 in the first place?

Tray2's avatar

@uniqueginun Ok,

The base64 has the filetype in the beginning of the code

'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/CABEIBkAFDgMBEQACEQEDEQH/xAA6AAABBAMBAQEBAAAAAAAAAAAEAAMFBgIHCAEJCgsBAQADAQEBAQEBAAAAAAAAAAACAwQFAQYHCAn/2gAMAwEAAhADEAAAALN9x+Tnriknx/oWPrHcbkjn2dHbFvuxn02fNPPu0f0Mf0TZ+l6z3PuersO0M

With some simple regex you should be able to extract the file type

'data:image/jpeg;base64,/9j/
1 like
uniqueginun's avatar

@Tray2 yeah here's the problem, they send me only what is after data:image/jpeg;base64,

martinbean's avatar

you mean the file type? no only plain base64 string

@uniqueginun I don’t believe that. Which API is this? Show an example of the API response.

You can’t just convert a Base64 string to a file without knowing what type of file it is. And there’s nothing stopping it being a harmful .EXE that’s going to pwn your server if you’re just blindly accepting files from third parties.

Snapey's avatar

Intervention image will accept base64 data and then you can save it in whatever format you want

Please or to participate in this conversation.