Skip to content

Instantly share code, notes, and snippets.

@anthonycoffey
Last active June 30, 2019 23:28
Show Gist options
  • Save anthonycoffey/59bc8114d735c32870a21670bc0f9c15 to your computer and use it in GitHub Desktop.
Save anthonycoffey/59bc8114d735c32870a21670bc0f9c15 to your computer and use it in GitHub Desktop.
Upload Base64 Image with PHP
$base64_img = $_POST['img'];
$split = explode(',', substr($base64_img, 5), 2);
$mime = $split[0];
$img_data = $split[1];
$mime_split_without_base64 = explode(';', $mime, 2);
$mime_split = explode('/', $mime_split_without_base64[0], 2);
if (count($mime_split) == 2) {
// get file extension
$extension = $mime_split[1];
// decode base64 string
$decoded = base64_decode($img_data);
// create filename
$filename = date('H-i-s') . '.' . $extension;
// returns falsy if unsuccessful
$upload_file = file_put_contents($upload_path . $filename, $decoded);
} else {
// data not formatted correctly
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment