Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php image file upload and convert to base64 without saving image

Tags:

I know how to upload image file and save to other location by using the following code. However, I need to do in such a way that user upload image and automatically convert to base64 without saving that image in my location. How should I do?

<?php
//print_r($_FILES);
if(isset($_FILES['image']))
{
    $errors=array();
    $allowed_ext= array('jpg','jpeg','png','gif');
    $file_name =$_FILES['image']['name'];
 //   $file_name =$_FILES['image']['tmp_name'];
    $file_ext = strtolower( end(explode('.',$file_name)));


    $file_size=$_FILES['image']['size'];
    $file_tmp= $_FILES['image']['tmp_name'];
    echo $file_tmp;echo "<br>";

    $type = pathinfo($file_tmp, PATHINFO_EXTENSION);
    $data = file_get_contents($file_ext);
    $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
    echo "Base64 is ".$base64;



    if(in_array($file_ext,$allowed_ext) === false)
    {
        $errors[]='Extension not allowed';
    }

    if($file_size > 2097152)
    {
        $errors[]= 'File size must be under 2mb';

    }
    if(empty($errors))
    {
       if( move_uploaded_file($file_tmp, 'images/'.$file_name));
       {
        echo 'File uploaded';
       }
    }
    else
    {
        foreach($errors as $error)
        {
            echo $error , '<br/>'; 
        }
    }
   //  print_r($errors);

}
?>


<form action="" method="POST" enctype="multipart/form-data">

<p>
    <input type="file" name="image" />
    <input type="submit" value="Upload">

</p>
</form>
like image 695
Khant Thu Linn Avatar asked Oct 12 '13 14:10

Khant Thu Linn


1 Answers

There is a mistake in your code:

$data = file_get_contents( $file_ext );

This should be:

$data = file_get_contents( $file_tmp );

This should solve your problem.

like image 121
halfpastfour.am Avatar answered Oct 11 '22 21:10

halfpastfour.am