Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is base64 valid in PHP

I have a string and want to test using PHP if it's a valid base64 encoded or not.

like image 845
Alias Avatar asked Nov 25 '10 14:11

Alias


People also ask

How do I check if a string is base64 encoded?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

Is base64 encoded PHP?

PHP | base64_encode() Function. The base64_encode() function is an inbuilt function in PHP which is used to Encodes data with MIME base64. MIME (Multipurpose Internet Mail Extensions) base64 is used to encode the string in base64. The base64_encoded data takes 33% more space then original data.

What does == mean in base64?

The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. Each group of six bits is encoded using the above conversion.


2 Answers

I realise that this is an old topic, but using the strict parameter isn't necessarily going to help.

Running base64_decode on a string such as "I am not base 64 encoded" will not return false.

If however you try decoding the string with strict and re-encode it with base64_encode, you can compare the result with the original data to determine if it's a valid bas64 encoded value:

if ( base64_encode(base64_decode($data, true)) === $data){     echo '$data is valid'; } else {     echo '$data is NOT valid'; } 
like image 194
PottyBert Avatar answered Oct 07 '22 12:10

PottyBert


You can use this function:

 function is_base64($s) {       return (bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s); } 
like image 28
Dennais Avatar answered Oct 07 '22 10:10

Dennais