How to upload image using base64 in php?

In this tutorial, we will let you know how to handle the image encoded with Base64 and write the image to folder. 
While we have working with API for mobile or web application , You will notice that they will send the format of images in Base64 encoded. So in that case, you will need to move the Base64 encoded image to server as a image file.and have to save it in the folder

Example Core PHP:

 

Upload base64 to file in Codeigniter 

Are you looking for a way to save a PNG image server-side, from a base64 data string, or unable to upload to a base64 encoded image using Codeigniter? We can help you with that.

We are creating some function for using base64 string check is valid or not and size and file type

create file application/libraries/Base64fileUploads.php

is_base64($base64string) == true 
        ){  
            $base64string = "data:image/jpeg;base64,".$base64string;
            $this->check_size($base64string);
            $this->check_dir($path);
            $this->check_file_type($base64string);
            
            /*=================uploads=================*/
            list($type, $base64string) = explode(';', $base64string);
            list(,$extension)          = explode('/',$type);
            list(,$base64string)       = explode(',', $base64string);
            $fileName                  = uniqid().date('Y_m_d').'.'.$extension;
            $base64string              = base64_decode($base64string);
            file_put_contents($path.$fileName, $base64string);
            return array('status' =>true,'message' =>'successfully upload !','file_name'=>$fileName,'with_path'=>$path.$fileName);
        }else{
            print_r(json_encode(array('status' =>false,'message' => 'This Base64 String not allowed !')));exit;
        }
    }
    
    public function check_size($base64string){
        $file_size = 8000000;
        $size = @getimagesize($base64string);
        
        if($size['bits'] >= $file_size){
            print_r(json_encode(array('status' =>false,'message' => 'file size not allowed !')));exit;
        }
        return true;
    }
    
    public function check_dir($path){
        if (!file_exists($path)) {
            mkdir($path, 0777, true);
            return true;
        }
        return true;
    }
    
    public function check_file_type($base64string){
        $mime_type = @mime_content_type($base64string);
        $allowed_file_types = ['image/png', 'image/jpeg', 'application/pdf'];
        if (! in_array($mime_type, $allowed_file_types)) {
            // File type is NOT allowed
           // print_r(json_encode(array('status' =>false,'message' => 'File type is NOT allowed !')));exit;
        }
        return true;
    }
}

Example Codeigniter :

Call this class Codeigniter in controller 


$base64file   = new Base64fileUploads();
$return = $base64file->du_uploads($this->data['document'],$document_front_site);

You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.

$data = 'data:image/png;base64,AAAFBfj42Pj4';

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);

file_put_contents('/tmp/image.png', $data);

And as a one-liner:

$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));

An efficient method for extracting, decoding, and checking for errors is:

if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
    $data = substr($data, strpos($data, ',') + 1);
    $type = strtolower($type[1]); // jpg, png, gif

    if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
        throw new \Exception('invalid image type');
    }
    $data = str_replace( ' ', '+', $data );
    $data = base64_decode($data);

    if ($data === false) {
        throw new \Exception('base64_decode failed');
    }
} else {
    throw new \Exception('did not match data URI with image data');
}

file_put_contents("img.{$type}", $data);

How to upload base64 image in folder PHP?

How to upload base64 to file in PHP.
$base64string = '';.
$uploadpath = 'upload/images/';.
$parts = explode(";base64,", $base64string);.
$imageparts = explode("image/", @$parts[0]);.
$imagetype = $imageparts[1];.
$imagebase64 = base64_decode($parts[1]);.
$file = $uploadpath . uniqid() . '. png';.

How to save base64 string as image in PHP?

you need to parse it. ... .
@Constantine Can you be more specific, please? ... .
$data = $_REQUEST['base64data']; $image = explode('base64,',$data); file_put_contents('img.png', base64_decode($image[1])); ... .
you can post the full code , from the snapshot and till you send the data, its not working for me..

How do I insert an image into base64?

How to embed base64 images in HTML.
Step 1 Convert image to base64 string. There are several ways to do this. Here is a Java example..
Step 2 Create an img tag with an empty src value..
Step 3 Construct a data URI in the src attribute..

How decode base64 in PHP?

The base64_decode() is an inbuilt function in PHP which is used to Decodes data which is encoded in MIME base64. Parameters: This function accepts two parameter as mentioned above and described below: $data: It is mandatory parameter which contains the encoded string. $strict: It is an optional parameter.