How to save base64 encoded image in a file using PHP
- <?php
- /// define upload directory
- define(‘UPLOAD_DIR’, ‘images/’);
- /// explode on ;base64 to know image type from encoded string
- $image_parts = explode(“;base64,”, $_POST[‘image’]);
- $image_type_aux = explode(“image/”, $image_parts[0]);
- $image_type = $image_type_aux[1];
- $image_base64 = base64_decode($image_parts[1]);
- /// create file path with file name
- $filepath = UPLOAD_DIR .’img_’. uniqid() . ‘.png’;
- /// put file to upload directory, please do not forget to double check directory permissions to write.
- file_put_contents($filepath, $image_base64);
- ?>