How to upload base64 image php? Uploading base64 encoded image in php.

In this article we will discuss about how to upload a base64 encoded image in php by specifying the url. If you want to upload an image from url checkout this link upload image from url.

HTML :

<!DOCTYPE html>
<html>
<head>
   <title>Base 64 image Upload</title>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body style="margin-left: 20%;margin-top: 10%;">
    <div class="row">
	<div class="col-md-4">
           <form action="<?=$_SERVER['PHP_SELF'];?>" method="post" enctype="multipart/form-data">
	      <div class="form-group">
	          <label>Image URL </label>
	          <input type="text" name="image" class="form-control">
	      </div>
	      <input type="submit" name="submit" value="Submit" class="btn btn-sm btn-info">
	    </form>
	 </div>
      </div>	
</body>
</html>

Create a form with method as POST, specify an input box to get base64 url

Include https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css file to get the exact design specified in this example.

PHP :

<?php
if(isset($_POST['submit']))
{
	$image = base64_decode($_POST['image']);
	$image_name = md5(uniqid(rand(), true));
	$filename = $image_name . '.' . 'jpg';
	$path = 'images/';
	file_put_contents($path . $filename, $image);
}
?>
  1. If form submitted, post the value of input box and do decode using base64_decode() function.
  2. Specify a unique randome generated name for image.
  3. Specify image upload path.
  4. Upload files using file_put_contents() function

Hope this article to upload base64 image php will help you.

Leave A Comment