How to save a base64 image from javascript with php

Sometimes, the user will be not able to select a file and attach it to a file input or you are implementing a feature with javascript that generates a base64 image (for example to take a snapshot from a user and save it in the server read more about this feature here). And "it's a bad idea" (in question of performance) to save a base64 string in your database, to handle images is easily to have files.

Probably you already know how to send the base64 image to the server, however some extra information doesn't hurt anyone :

How to send a base64 to the server

Generally, you can use a simple form and a textarea (since the base64 image can be too long), then use javascript to save the generated base64 on the texarea and retrieve it later on the server.

<!-- Note that you need to submit the form (or the ajax) with post method,
because the base64 can be too long for use the get method -->


<canvas id="myCanvasImage" width="500" height="500"></canvas>

<form method="POST" name="form" id="form">
  <textarea name="base64" id="base64"></textarea>
  <button type="submit">
    Send image
  </button>
</form>

<script>

   // on the submit event, generate a image from the canvas and save the data in the textarea
   document.getElementById('form').addEventListener("submit",function(){
      var canvas = document.getElementById("myCanvasImage");
      var image = canvas.toDataURL(); // data:image/png....
      document.getElementById('base64').value = image;
   },false);

</script>

Or if you don't want to use a form, simply use ajax :

var image = "data:image/png;base64,BBBFBfj42Pj4"; // to create a image read the previous example

$.ajax({
  url:"service/url/process.php",
  // send the base64 post parameter
  data:{
    base64: image
  },
  // important POST method !
  type:"post",
  complete:function(){
    console.log("Ready");
  }
});

Save base64 string as image with PHP

The backend part is really easy to handle, the only part you need to figure it out is how to retrieve the string from the request ($_POST or the way you retrieve post info with your favorite framework).

// baseFromJavascript will be the javascript base64 string retrieved of some way (async or post submited)
$baseFromJavascript = "data:image/png;base64,BBBFBfj42Pj4"; // $_POST['base64']; //your data in base64 'data:image/png....';
// We need to remove the "data:image/png;base64,"
$base_to_php = explode(',', $baseFromJavascript);
// the 2nd item in the base_to_php array contains the content of the image
$data = base64_decode($base_to_php[1]);
// here you can detect if type is png or jpg if you want
$filepath = "/path/to/my-files/image.png"; // or image.jpg

// Save the image in a defined path
file_put_contents($filepath,$data);

Note: You can simplify the previous code using a regular expression:

$baseFromJavascript = "data:image/png;base64,BBBFBfj42Pj4";

// remove the part that we don't need from the provided image and decode it
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $baseFromJavascript));

$filepath = "/path/to/my-files/image.png"; // or image.jpg

// Save the image in a defined path
file_put_contents($filepath,$data);

If you have the known problem of the black background on the image when saving it to the server, remember to save it as png, read more about this issue here, have fun !

Become a more social person