Skip to content

Instantly share code, notes, and snippets.

@pixelbacon
Last active January 10, 2017 17:20
Show Gist options
  • Save pixelbacon/0e1b409b58967267607c to your computer and use it in GitHub Desktop.
Save pixelbacon/0e1b409b58967267607c to your computer and use it in GitHub Desktop.
Decode json base64 file string.
<?php
/**
* Takes a base64 encoded file string and returns usable information, including the re-encoded file.
* Very useful for absorbing files over JSON.
* @param $str
* @return array
* @throws Exception
*/
function base64FileDecode($str)
{
$file_parts = explode(',', $str);
$file_encoding = explode(';',$file_parts[0])[1];
$file_type = explode(':', explode(';',$file_parts[0])[0])[1];
$file = $file_parts[1];
$file = str_replace(' ','+',$file);
$file_decoded = base64_decode($file);
if($file_encoding != 'base64'){
throw new Exception('Did not detect a base64 encoded string');
}
return array(
"file" => $file_decoded,
"type" => $file_type,
"string" => $file
);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment