Is there some way to detect if a string has been base64_encoded() in PHP?
We're converting some storage from plain text to base64 and part of it lives in a cookie that needs to be updated. I'd like to reset their cookie if the text has not yet been encoded, otherwise leave it alone.
Here's my solution:
if(empty(htmlspecialchars(base64_decode($string, true)))) { return false; }
It will return false if the decoded
$string
is invalid, for example: "node", "123", " ", etc.May be it's not exactly what you've asked for. But hope it'll be usefull for somebody.
In my case the solution was to encode all data with json_encode and then base64_encode.
this value could be stored or used whatever you need. Then to check if this value isn't just a text string but your data encoded you simply use
or alternatively
Thanks to all previous answers authors in this thread:)
Better late than never: You could maybe use
mb_detect_encoding()
to find out whether the encoded string appears to have been some kind of text:We can combine three things into one function to check if given string is a valid base 64 encoded or not.
Your best option is: