John Davidson

php - Validate if use base 64 and problem with equal

0 comments
Message:


I have problem for verificate if line use base64 encode, because the problem it´s with equal, for save data in base64 i need don´t show equal, but the same time i need validate if value it´s encode with base 64


I use this function :


function is_base64_encoded($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) print "false"; return false;

// Encode the string again
if(base64_encode($decoded) != $s) return false;
return true;
}

The Function works fine, the problem it´s if i replace "=" the function don´t detect base64, etc


By this, my question it´s about how identificate if base64 encoded it´s ok if replace "="


For example Base64 Encode :


This it´s the best car 1980
VGhpcyBpdMK0cyB0aGUgYmVzdCBjYXIgMTk4MA==

The same example if replace "=" :


This it´s the best car 1980
VGhpcyBpdMK0cyB0aGUgYmVzdCBjYXIgMTk4MA

The problen it´s the function for detect if it´s base64 enconde don´t works without "=" and show as line don´t use Base64


By this i find complicated how detect if line it´s encode with Base64 if i replace "=", and i need don´t show "=" and detect if use Base64.


Thank´s in advanced and i hope can help me, regards



My Answer:
"Invalid base64 encoding";
return false;
}

return base64_encode($decoded) === $s;
}

This function first checks if the input string contains valid base64 characters using a regular expression. If it does not, it returns false. Then, it decodes the string using base64_decode() in strict mode and checks if the decoded value matches the original input string after encoding it again. If they match, it returns true, indicating that the input string is indeed base64 encoded.

Rate this post

5 of 5 based on 3336 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us