base64_decode for image

In the blog post about using base64_encode for encoding an image , I talked about how to encode the image using base64 encode method of php.

In this post let us look at base 64 decoding function.

If you want to send an image using Ajax or from any other system, one of the ways is first encoding the image in base 64 mime type. This encoding can be done in any language ( php, javascript or java ) but it should result in the same string.

The data you would receive would start with




Using base_64encode for images

The primary problem of a developer is

How to send image from the front end to the back end server which is running on PHP.

So the process goes like this

1> Create a form in HTML to allow user to add an image

<form action ="imageLoader.php" method="post" encType ="multipart/form-data">

<input type ="file" name="myImage" />

<input type="submit" name="submit" />


The requirement is to display the file in another script.

In PHP script imageLoader.php

$_FILES will provide the file name which can be copied to another location and then read using file_get_contents()

$content = file_get_contents("myfile.png");

$base64String = base64_encode($content);

Based on the type type add

Then the base64String can be re-sent to the server using a script like this

header('Content-Type: application/json');

echo json_encode($base64String);


Don’t forget to include die(); otherwise anything after the script will be sent as well

Breaking out of a loop

A loop can be defined as

<br data-mce-bogus="1">

for($i = 1; $i&lt;10;$i++){

// Do something


Let us consider that application logic dictates that when we $i ==5 , then we exit the loop

for($i = 1; $i<10;$i++){

// Do something

if($i == 5)



We can apply the same thing in while



if($i == 5)




It is better to put the break condition as

if(5==$i) because many a developers have been ruined by this

if ($i=5) ( missing “=” )

isset() vs empty()

isset() usage

Example 1:

$post['var'] = 100;

isset($post[‘var’]) will return true

Example 2:

isset($name) will return false if $name has not been declared

Example 3:

$post['v1'] = 100;

isset($post[‘v2’]) will return false

since isset is not assigned


It essentially means

!isset($var) || $var == false.

So it is either is not set or it is set but its value is false

Example 1

$post['v1'] = 100;

empty($post[‘v1’]) is false

Example 2

$post['v2'] = false

empty($post[‘v2’])  is true

Example 3

empty($post[‘v3’]) is true because $post[‘v3] has not been declared