Base64 decode file upload php

I'm passing image as a base64 string from a form. Then I would like to decode it, rename it and upload it to my server folder. I can't get this to work so obviously I'm doing something wrong here. Any help would be appreciated.

My code:

$image = $_POST['image-data'];//base64 string of a .jpg image passed from form:

$image = str_replace('data:image/png;base64,', '', $image);//Getting rid of the start of the string:
$image = str_replace(' ', '+', $image);
$image = base64_decode($image);

$ext = strtolower(substr(strrchr($image, '.'), 1)); //Get extension of image

$lenght = 10;
$image_name = substr(str_shuffle("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ"), 0, $lenght);

$image_name = $image_name . '.' . $ext; //New image name

$uploaddir = '/var/www/vhosts/mydomain.com/httpdocs/img/'; //Upload image to server
$uploadfile = $uploaddir . $image_name;
move_uploaded_file('$image', $uploadfile);

asked Aug 31, 2017 at 12:13

2

Using file put content you can move files to folder

$file = $_POST['image-data'];
$pos = strpos($file, ';');
$type = explode(':', substr($file, 0, $pos))[1];
$mime = explode('/', $type);

$pathImage = "path to move file/".time().$mime[1];
$file = substr($file, strpos($file, ',') + 1, strlen($file));
$dataBase64 = base64_decode($file);
file_put_contents($pathImage, $dataBase64);

Base64 decode file upload php

Rodrirokr

1,27715 silver badges26 bronze badges

answered Aug 31, 2017 at 12:22

Base64 decode file upload php

ShibonShibon

1,4692 gold badges8 silver badges19 bronze badges

1

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);