
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.
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.
2. Enter your project name, check on the terms and conditions check box, and click on the continue button.
3. On step three click on the continue button and proceed.
4. Select your country in the location dropdown, check all three checkboxes, and click on the create project button.
5. After clicking the create project button you have received a message “Your new project is ready“.
6. Click on the continue button to redirect the firebase dashboard.
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.
Click on the rule tab and replace the below script to change the access.
For Non-authentication Rules
1 2 3 4 5 6 7 |
service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write; } } } |
For Authentication Rules
1 2 3 4 5 6 7 |
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
1 2 3 |
<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.
1 2 3 4 5 6 7 8 9 10 11 |
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 ); |
Create the database table in the MySQL database to store the image path. The Create table script looks like this.
1 2 3 4 5 6 |
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; |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<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 following Javascript will upload the images to the Firebase storage and return the uploaded image path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
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" ); } ); } |
Writing the PHP upload code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
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(); } }<gwmw style="display:none;"><gwmw style="display:none;"><gwmw style="display:none;"></gwmw><gwmw style="display:none;"> |
Important Files Name
Create index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 |
<?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">×</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">×</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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<?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(); } } } |
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.
3 replies on “How to upload images on Firebase Storage Download”
Hello, I was trying to run the project, but I couldn’t upload the firebase image to a database, I would appreciate it if you could upload the code to download it back, thank you very much in advance for your help
I am already uploaded. Please check the below link
Firebase Source code
Hi i cant download the source code