Skip to content

Instantly share code, notes, and snippets.

@ge0ffray
Last active August 8, 2024 11:02
Show Gist options
  • Save ge0ffray/2048791 to your computer and use it in GitHub Desktop.
Save ge0ffray/2048791 to your computer and use it in GitHub Desktop.
Check if a string seems to be base64 encoded
<?php
/**
* @param string $str
* @return bool
*/
function is_base64($str)
{
return (bool)preg_match('`^[a-zA-Z0-9+/]+={0,2}$`', $str);
}
@edmunds22
Copy link

edmunds22 commented Aug 8, 2024

A slightly adapted version incase anyone is validating base64 encoded files (not fully tested):

private function isBase64Encoded(string $s): bool
  {
    if ((bool) preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s) === false) {
      return false;
    }

    $decoded = base64_decode($s, true);
    if ($decoded === false) {
      return false;
    }

    $mimeType = finfo_buffer(finfo_open(), $decoded, FILEINFO_MIME_TYPE);

    return $decoded !== false && base64_encode($decoded) === $s && $mimeType;
  } 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment