Search

How to upload base64 to file in PHP

  • Share this:
post-title

How to upload base64 to file 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:

<?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';
    file_put_contents($file, $imagebase64);
?> 

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

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Base64fileUploads { 
    
    function is_base64($s){
        // Check if there are valid base64 characters
       // if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $s)) return false;
        // Decode the string in strict mode and check the results
        $decoded = base64_decode($s, true);
        if(false === $decoded) return false;
        // Encode the string again
        if(base64_encode($decoded) != $s) return false;
        return true;
    }
    
    public function du_uploads($path,$base64string){
        if(
            $this->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);

 

About author
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming.
View all posts (53)