PHP Web Development

Base64 encoded image save by PHP

How to save base64 encoded image in a file using PHP

  1. <?php
  2.  /// define upload directory
  3.     define(‘UPLOAD_DIR’, ‘images/’);
  4. /// explode  on ;base64  to know image type from encoded string
  5.    $image_parts = explode(“;base64,”, $_POST[‘image’]);
  6.     $image_type_aux = explode(“image/”, $image_parts[0]);
  7.     $image_type = $image_type_aux[1];
  8.     $image_base64 = base64_decode($image_parts[1]);
  9.    /// create file path with file name
  10.     $filepath = UPLOAD_DIR .’img_’. uniqid() . ‘.png’;
  11.   /// put file to upload directory, please do not forget to double check directory permissions to write.
  12.     file_put_contents($filepath, $image_base64);
  13. ?>

Leave a Reply

Your email address will not be published. Required fields are marked *


CAPTCHA Image
Reload Image