Skip to content

Instantly share code, notes, and snippets.

@alexcorvi
Last active June 29, 2016 12:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexcorvi/f10d13515400e1231873ea4ce0b6a55f to your computer and use it in GitHub Desktop.
Save alexcorvi/f10d13515400e1231873ea4ce0b6a55f to your computer and use it in GitHub Desktop.
will only decode the data if it's base64 (or a base64 data URI), if it's not will return the same data, also used to check if it's base64 or a data URI.
function decode_if_b64($file_content="",$return_boolean=false) {
/**
*
* Base64 files handling
* 1. first we'll check if it's a base64 data URI
* and we'll strip the data uri initials
*
* 2. Confirm it using regular expression
*
* 3. Confirm it again with PHP base64_decode() function
*
* 4. Decode it
*
**/
// it's not, unless proven otherwise
$is_base64 = false;
$is_data_uri = false;
// initials
$indi_pos1 = strpos($file_content,"data:");
$indi_pos2 = strpos($file_content,";base64,");
if(($indi_pos1 !== false) && ($indi_pos2 !== false)) {
// it's base64 data URI.
// strip out those initails
$file_content_striped = substr($file_content,$indi_pos2+8);
$is_data_uri = true;
/**
*
* Note how we're saving the stripped data into a new string not mutilitaing the original
* file contents, until we have other checks returns true.
*
* this userful incase of text files that has the string ;base64, in them.
*
**/
}
$base64_preg_check = preg_match("~^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$~",$file_content_striped);
// confirm with regular expression
if($base64_preg_check){
$decodedBase64 = base64_decode($file_content_striped,true);
// if decoding was done correctly with no errors
if($decodedBase64) {
$file_content = $decodedBase64;
$is_base64 = true;
}
/**
* Note: we could have relied on the base64_decode to check if it's really a base64 file.
* but, for performance issues we'll only try to decode if the file is matched the regular expresion
* since regular expression matching is faster than base64_decode function.
*
**/
}
if($return_boolean) $return_data = array(
"base64" => $is_base64,
"dataURI" => $is_data_uri,
"file" => $file_content
);
else $return_data = $file_content;
return $return_data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment