How to upload images on Firebase Storage Download

Upload images on Firebase Storage

Upload images on Firebase Storage

In this tutorial, We’re going to learn how to Upload images on Firebase Storage from a web application and store the image path in MySQL database using javascript and curl PHP. Also, we can show the progress bar of uploading an image to the end-user. Once the document is successfully uploaded in the firebase storage, the Firebase storage returns the URL of that uploaded file so that we can access the URL through a hyperlink or store it in the database and show it as per our requirement.

What is Firebase?

Firebase is an app-development platform on Google Cloud Platform development launched in 2011 by Firebase and acquired by Google in 2014. Started with the Firebase Realtime Database and API that synchronizes software data across Android, and Web applications and stores it on the firebase cloud server. The Firebase is used for application development on a cloud platform.

How to create the Firebase project?

The following steps to create the Firebase project.

  1. Create a Firebase Project: Before starting any project we need to create a Firebase project on the Google Cloud to connect to your website or mobile app. Open the Google Firebase URL and click on the Create Project button.
Create a Firebase Project

2. Enter your project name, check on the terms and conditions check box, and click on the continue button.

Create a Firebase Project

3. On step three click on the continue button and proceed.

create the Firebase project

4. Select your country in the location dropdown, check all three checkboxes, and click on the create project button.

create the Firebase project

5. After clicking the create project button you have received a message “Your new project is ready“.

create the Firebase project

6. Click on the continue button to redirect the firebase dashboard.

create the Firebase project

How to enable Firebase Storage in the Firebase project?

How to enable Firebase Storage in the Firebase project

Open your Firebase console and select your project and click on the storage link which is available on the left menu. Follow the given instruction on the webpage.
After creating the storage in firebase we need to set the rules to access firebase storage with authentication.

But now in this tutorial, I will skip the authentication part and explain the simple Firebase image upload functionality.

How to enable Firebase Storage in the Firebase project

Click on the rule tab and replace the below script to change the access.

For Non-authentication Rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

For Authentication Rules

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

After adding the above code click on the publish button. Now your configuration is ready to use.

Include the below Javascript library on the header section

<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>

<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>

Copy the below Firebase configuration object and paste it on the footer section of your web page.

const firebaseConfig = {
		apiKey: "YOUR_API_KEY",
		authDomain: "YOUR_AUTH_DOMAIN",
		projectId: "PROJECT_ID",
		storageBucket: "STORAGE_BUCKET",
		messagingSenderId: "MESSAGING_SENDER_ID",
		appId: "YOUR_APP_ID",
		measurementId: "G-MEASUREMENT_ID"
	};
	// Initialize Firebase
	firebase.initializeApp( firebaseConfig );
Firebase configuration object

Creating the Database Table

Create the database table in the MySQL database to store the image path. The Create table script looks like this.

CREATE TABLE IF NOT EXISTS `imagepath` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `imgName` varchar(500) NOT NULL,
  `filePath` varchar(1000) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

Creating the HTML form

Image uploaded in Firebase storage using JavaScript

Create the HTML form to browse the images from your local folder and upload them on Firebase storage using Javascript.

The HTML code looks like this.

<form method='post' enctype="multipart/form-data">
<div class="form-row">
	<div class="form-group col-md-3 txtAlign">
		<label>Image Name</label>
	</div>
	<div class="form-group col-md-8">
		<input type="text" class="form-control" name="imgName" placeholder="Image Name" required>
	</div>
</div>
<div class="form-row">
	<div class="form-group col-md-3 txtAlign">
		<label>Select Image</label>
	</div>
	<div class="form-group col-md-8">
		<input type="file" id="files" name="imgDoc" required class="form-control">
		<p class="help-block">Only jpeg, jpg, png and tiff can be uploaded</p>
		<textarea id="urlUP" name="filePath" hidden="hidden"></textarea>
		<progress value="0" max="100" id="progress" class="progressbar"></progress>
		<p id="uploading" class="successMsg"></p>
	</div>
</div>
<div class="form-row">
	<div class="form-group col-md-3">

	</div>
	<div class="form-group col-md-8">
		<input type="submit" class="btn btn-primary" name="imgUplaod" value="Submit">
		<img src="" id="profile-img-tag" class="displayImg"/>
	</div>
</div>
</form>
<div class="col-md-6">
<div class="form-row">
	<div class="form-group col-md-1">
		<button type="submit" class='btn btn-success btn-sm uploadBtn' id="uploadImg">
			<i class="fas fa-upload"></i> Upload</button>
	

	</div>
	<div class="form-group col-md-9">
		<p class="heading"><strong>Instructions:</strong>
		</p>
		<ul>
			<li>Provide the name of Image.</li>
			<li>Select image via Choose Files.</li>
			<li>Click on Upload button.</li>
			<li>Submit the Form to store the image path in MySQL database.</li>
		</ul>
	</div>
</div>
					</div>

The Javascript Code

The following Javascript will upload the images to the Firebase storage and return the uploaded image path.

var files = [];
	document.getElementById( "files" ).addEventListener( "change", function ( e ) {
		files = e.target.files;
		for ( let i = 0; i < files.length; i++ ) {
			console.log( files[ i ] );
		}
	} );

	document.getElementById( "uploadImg" ).addEventListener( "click", function () {

		//checks if files are selected
		if ( files.length != 0 ) {
			//Loops through all the selected files
			for ( let i = 0; i < files.length; i++ ) {
				//create a storage reference
				var storage = firebase.storage().ref( 'images/' + files[ i ].name );
				//upload file
				var upload = storage.put( files[ i ] );

				//update progress bar
				upload.on(
					"state_changed",
					function progress( snapshot ) {
						var percentage =
							( snapshot.bytesTransferred / snapshot.totalBytes ) * 100;
						document.getElementById( "progress" ).value = percentage;
					},

					function error() {
						alert( "error uploading file" );
					},

					function complete() {
						document.getElementById(
							"uploading"
						).innerHTML += `Document uploaded successfully.`;
						getFileUrl( 'images/' + files[ i ].name );
					}
				);
			}
			//evt.preventDefault();
		} else {
			alert( "File is not selected." );
		}
	} );

	function getFileUrl( filename ) {
		//create a storage reference
		var storage = firebase.storage().ref( filename );

		//get file url
		storage
			.getDownloadURL()
			.then( function ( url ) {
				document.getElementById(
					"urlUP"
				).innerHTML += `${url}`;
				console.log( url );
			} )
			.catch( function ( error ) {
				console.log( "error encountered" );
			} );
	}

The PHP Code

Writing the PHP upload code.

if ( isset( $_POST[ 'imgUplaod' ] ) ) {

	$imgName = $_POST[ 'imgName' ];
	$filePath = $_POST[ 'filePath' ];
	if ( $filePath <> "" ) {
		$user_data->imgRecord( $imgName, $filePath );
		$succesMSG ="Image Path inserted successfully";

	} else {

		$errorMSG = "Something went wrong.";
	}

}
<!---------- Writing Insert Query in PHP PDO --------------->
public function imgRecord($imgName, $filePath)
	{
		try
		{	
			
			$stmt = $this->conn->prepare("INSERT INTO imagepath(imgName,filePath) 
			       VALUES(:imgName1,:filePath1)");
			$stmt->bindparam(":imgName1",$imgName);
			$stmt->bindparam(":filePath1",$filePath);
			if($stmt->execute()) {
				$succesMSG= "Image Path inserted successfully";
				return true;
				
				}	
				else {
				$$errorMSG= "Something Went Wrong.";
				}
			
		}
		catch(PDOException $ex)
		{
			echo $ex->getMessage();
		}
	}
Image uploaded in Firebase storage using JavaScript php

Full Source Code

Important Files Name

  1. index.php
  2. dbconfig.php
  3. common.php

Create index.php

<?php
ob_start();
require __DIR__ . DIRECTORY_SEPARATOR . "lib" . DIRECTORY_SEPARATOR . "config.php";
// HTML
require PATH_LIB . "page-top.php";
if ( isset( $_POST[ 'imgUplaod' ] ) ) {

	$imgName = $_POST[ 'imgName' ];
	$filePath = $_POST[ 'filePath' ];
	if ( $filePath <> "" ) {
		$user_data->imgRecord( $imgName, $filePath );
		$succesMSG ="Image Path inserted successfully";

	} else {

		$errorMSG = "Something went wrong.";
	}

}
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
	.uploadBtn {
		margin-top: 60px;
		margin-left: -60px;
	}
	
	.heading {
		font-size: 20px;
		font-weight: bold;
	}
	
	.successMsg {
		color: #059c27;
		font-size: 14px;
	}
	
	.progressbar {
		background: #28a745!important;
		width: 100%;
	}
	
	.txtAlign {
		text-align: right;
	}
	
	.displayImg {
		width: 100%;
	}
	.imgGrid{
		width: 100%;
    border: 1px solid #ccc;
    padding: 10px;
	}
</style>
<section class="testimonial py-3" id="testimonial">
	<div class="container">
		<div class="row">
			<div class="col-md-12 py-3 border rounded shadow-sm">
				<h4 class="pb-4 text-center">Firebase php curl</h4>
				<div class="row">
					<div class="col-md-6">
<div class="box-body msg-box">
<?php
if ( isset( $errorMSG ) ) {
	?>
<div class="alert alert-danger alert-dismissible">
	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
	<h4 style="font-size: 15px;">
		<?php echo $errorMSG; ?>
	</h4>

</div>
<?php
} else if ( isset( $succesMSG ) ) {
	?>
<div class="alert alert-success alert-dismissible">
	<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
	<h4 style="font-size: 15px;">
		<?php echo $succesMSG; ?>
	</h4>

</div>
<?php
}
?>
					</div>
<form method='post' enctype="multipart/form-data">
	<div class="form-row">
		<div class="form-group col-md-3 txtAlign">
			<label>Image Name</label>
		</div>
		<div class="form-group col-md-8">
			<input type="text" class="form-control" name="imgName" placeholder="Image Name" required>
		</div>
	</div>
	<div class="form-row">
		<div class="form-group col-md-3 txtAlign">
			<label>Select Image</label>
		</div>
		<div class="form-group col-md-8">
			<input type="file" id="files" name="imgDoc" required class="form-control">
			<p class="help-block">Only jpeg, jpg, png and tiff can be uploaded</p>
			<textarea id="urlUP" name="filePath" hidden="hidden"></textarea>
			<progress value="0" max="100" id="progress" class="progressbar"></progress>
			<p id="uploading" class="successMsg"></p>
		</div>
	</div>
	<div class="form-row">
		<div class="form-group col-md-3">

		</div>
		<div class="form-group col-md-8">
			<input type="submit" class="btn btn-primary" name="imgUplaod" value="Submit">
			<img src="" id="profile-img-tag" class="displayImg"/>
		</div>
	</div>

</form>
					</div>
					<div class="col-md-6">
<div class="form-row">
	<div class="form-group col-md-1">
		<button type="submit" class='btn btn-success btn-sm uploadBtn' id="uploadImg">
			<i class="fas fa-upload"></i> Upload</button>
	

	</div>
	<div class="form-group col-md-9">
		<p class="heading"><strong>Instructions:</strong>
		</p>
		<ul>
			<li>Provide the name of Image.</li>
			<li>Select image via Choose Files.</li>
			<li>Click on Upload button.</li>
			<li>Submit the Form to store the image path in MySQL database.</li>
		</ul>
	</div>
</div>
					</div>
				</div>
			</div>
		</div>

	</div>
</section>
<section class="testimonial py-3" id="testimonial">
	<div class="container">
		<div class="row">
			<div class="col-md-12 py-3 border rounded shadow-sm">
				<h4 class="pb-4 text-center">Download Images</h4>
				<div class="row">
					<?php
	$result = $DB_con->prepare("SELECT * FROM imagepath");
		$result->execute();
	 	$user_arr = array();
		for($i=0; $row = $result->fetch(); $i++){
	  ?>
					<div class="col-md-2">
<a href="<?php echo $row ['filePath'];?>" target="_blank"><img src="<?php echo $row ['filePath'];?>" alt="<?php echo $row ['imgName'];?>" class="imgGrid" /></a>
					</div>
					<?php } ?>
				</div>
			</div>
		</div>
</section>
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>

<!-- TODO: Add SDKs for Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-storage.js"></script>
<script>
	// Your web app's Firebase configuration
	// For Firebase JS SDK v7.20.0 and later, measurementId is optional
	const firebaseConfig = {
		apiKey: "AIzaSyBxert2k7D-I0QBQ5uJQLrsw63yqciaEWE",
		authDomain: "htmlcsstutorials-ccb5d.firebaseapp.com",
		projectId: "htmlcsstutorials-cdds",
		storageBucket: "htmlcsstutorials-ccb5d.appspot.com",
		messagingSenderId: "7822238704737",
		appId: "1:782538704737:web:e0acse236ac002b3b6720",
		measurementId: "G-V2Ced94WNGTQ"
	};
	// Initialize Firebase
	firebase.initializeApp( firebaseConfig );
</script>

<script>
	var files = [];
	document.getElementById( "files" ).addEventListener( "change", function ( e ) {
		files = e.target.files;
		for ( let i = 0; i < files.length; i++ ) {
			console.log( files[ i ] );
		}
	} );

	document.getElementById( "uploadImg" ).addEventListener( "click", function () {

		//checks if files are selected
		if ( files.length != 0 ) {
			//Loops through all the selected files
			for ( let i = 0; i < files.length; i++ ) {
				//create a storage reference
				var storage = firebase.storage().ref( 'images/' + files[ i ].name );
				//upload file
				var upload = storage.put( files[ i ] );

				//update progress bar
				upload.on(
					"state_changed",
					function progress( snapshot ) {
var percentage =
	( snapshot.bytesTransferred / snapshot.totalBytes ) * 100;
document.getElementById( "progress" ).value = percentage;
					},

					function error() {
alert( "error uploading file" );
					},

					function complete() {
document.getElementById(
	"uploading"
).innerHTML += `Document uploaded successfully.`;
getFileUrl( 'images/' + files[ i ].name );
					}
				);
			}
			//evt.preventDefault();
		} else {
			alert( "File is not selected." );
		}
	} );

	function getFileUrl( filename ) {
		//create a storage reference
		var storage = firebase.storage().ref( filename );

		//get file url
		storage
			.getDownloadURL()
			.then( function ( url ) {
				document.getElementById(
					"urlUP"
				).innerHTML += `${url}`;
				console.log( url );
			} )
			.catch( function ( error ) {
				console.log( "error encountered" );
			} );
	}
</script>
<script type="text/javascript">
	function readURL( input ) {
		if ( input.files && input.files[ 0 ] ) {
			var reader = new FileReader();

			reader.onload = function ( e ) {
				$( '#profile-img-tag' ).attr( 'src', e.target.result );
			}
			reader.readAsDataURL( input.files[ 0 ] );
		}
	}
	$( "#files" ).change( function () {
		readURL( this );
	} );
</script>
<?php ob_end_flush(); require PATH_LIB . "page-bottom.php"; ?>

Create dbconfig.php

class Database
{
     
    private $host = "localhost";
    private $db_name = "demotutorials";
    private $username = "root";
    private $password = "";
    public $conn;
     
    public function dbConnection()
	{
     
	    $this->conn = null;    
        try
		{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
			$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);	
        }
		catch(PDOException $exception)
		{
            echo "Connection error: " . $exception->getMessage();
        }
         
        return $this->conn;
    }
}

Creating common.php

<?php
session_start();
require_once 'dbconfig.php';
class ADMIN
{	
	private $conn;
	public function __construct()
	{
		$database = new Database();
		$db = $database->dbConnection();
		$this->conn = $db;
    }
	
	public function runQuery($sql)
	{
		$stmt = $this->conn->prepare($sql);
		return $stmt;
	}
	
	public function lasdID()
	{
		$stmt = $this->conn->lastInsertId();
		return $stmt;
	}
	
	
	public function imgRecord($imgName, $filePath)
	{
		try
		{	
			
			$stmt = $this->conn->prepare("INSERT INTO imagepath(imgName,filePath) 
			       VALUES(:imgName1,:filePath1)");
			$stmt->bindparam(":imgName1",$imgName);
			$stmt->bindparam(":filePath1",$filePath);
			if($stmt->execute()) {
				$succesMSG= "Image Path inserted successfully";
				return true;
				
				}	
				else {
				$$errorMSG= "Something Went Wrong.";
				}
			
		}
		catch(PDOException $ex)
		{
			echo $ex->getMessage();
		}
	}
}
Images in Firebase storage using Javascript, PHP, and MySQL

Conclusion

Congratulations! You’ve successfully uploaded the images in Firebase storage using Javascript, PHP, and MySQL. You can modify this code as per your requirement.

If you enjoyed this tutorial so please do not forget to share on social media.

For demo and source code please check out the demo and download link.