I am currently working on a Website where I have mixed values stored in my db and I'd like to find a solution to detect a string for base64 encryption or not. I've come up with this piece of code so far with help from Abhinav bhardwaj on this post (Detect base64 encoding in PHP?):
function IsBase64($s)
{
// Check if there are valid base64 characters
if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) return false;
// Decode the string in strict mode and check the results
$decoded = base64_decode($s, true);
if(false === $decoded) return false;
// if string returned contains not printable chars
if (0 < preg_match('/((?![[:graph:]])(?!\s)(?!\p{L}))./', $decoded, $matched)) return false;
// Encode the string again
if(base64_encode($decoded) != $s) return false;
return true;
}
It only works halfway for example values like 1234, 7000, reno and other 4-lettered and digited inputs resolve as true even if they are not... Now my question: Is there any reliable way of doing the base64 detection or do i have to keep a list of unencoded and encoded tables and treat them different?
My Plan would have been to merge the data (which some of it needs decryption and some doesn't) together in the end to one php result object and return it as a JSON text.
Any help on this is much appreciated!
Thank you in advanced!
EDIT : After Yoshi's Answering i want to pin my conclusion on the top for others that are looking for a easy solution to encode/decode specific data:
I think the best way would rather be, to keep the encoded data under a specific key in the db and look out in the query dataset result if this specific key is contained to keep track of the content that needs to be decrypted...
FYI: I have updated my Website to this behaviour and i have to admit it works like a charm!