Upload Image With Form Path to Mysql Database

PHP File Upload to Server with MySQL Database

by Vincy. Last modified on Feb 1st, 2022.

File upload is an important component in building websites. This article will help you lot to implement a file upload to the server feature with PHP and a MySQL database.

Example utilize cases of where the file upload may exist needed in a website,

  • Photo upload via member profile folio.
  • Import CSV or Excel to Database to insert bulk data.
  • Take documents like KYC, CV from the user via a class.

Let us see how to code PHP file upload for a website. You lot can dissever this commodity into the post-obit sections.

  1. PHP file upload – A quick example.
  2. File upload – server-side validation.
  3. Upload file to the server with database.
  4. Upload file as a hulk to the database.

PHP file upload – Quick example

<?php  if (isset($_FILES['upload_file'])) {     move_uploaded_file($_FILES["upload_file"]["tmp_name"], $_FILES["upload_file"]["name"]); } ?> <form name="from_file_upload" action="" method="post" 	enctype="multipart/form-data"> 	<div class="input-row"> 		<input type="file" name="upload_file" accept=".jpg,.jpeg,.png"> 	</div> 	<input blazon="submit" proper noun="upload" value="Upload File"> </form>          

This quick case shows a elementary code to reach PHP file upload. It has an HTML form to cull a file to upload. Allow the form with the following attributes for supporting file upload.

  1. method=post
  2. enctype=multipart/class-information

By choosing a file, it will exist in a temporary directory. The $_FILES["upload_file"]["tmp_name"] has that path. The PHP move_uploaded_file() uploads the file from this path to the specified target.

$_FILES['<file-input-proper noun>']['tmp_name'] PHP file upload temporary path
$_FILES['<file-input-name>']['name'] File name with extension
$_FILES['<file-input-proper noun>']['type'] File MIME blazon. Eg: image/jpeg
$_FILES['<file-input-name>']['size'] File size (in bytes)
$_FILES['<file-input-name>']['error'] File upload fault code if whatsoever
$_FILES['<file-input-proper name>']['full_path'] Full path as sent by the browser

The form allows multi-file upload past having an array of file input.

PHP file upload configuration

Ensure that the server environment has enough settings to upload files.

  • Check with the php.ini file if the file_uploads = on. Generally, it will be on past default.

More optional directives to change the default settings

  • upload_tmp_dir – to change the organisation default.
  • upload_max_filesize – to exceed the default limit.
  • max_file_uploads – to break the per-request file upload limit.
  • post_max_size – to breaks the POST information size.
  • max_input_time – to set the limit in seconds to parse request data.
  • max_execution_time – time in seconds to run the file upload script.
  • memory_limit – to set the memory limit in bytes to exist allocated.

File upload – server-side validation

When file uploading comes into the motion picture, then there should be proper validation. It volition prevent unexpected responses from the server during the PHP file upload.

This code checks the following iv weather before moving the file to the target path. It validates,

  • If the file is not empty.
  • If the file does not already be in the target.
  • If the file type is ane of the immune extensions.
  • If the file is within the limit.

It shows only the PHP script for validating the uploaded file. The form HTML will be the same as that of the quick example.

file-upload-validation.php

<?php if (isset($_POST["upload"])) {     // Validate if not empty     if (!empty($_FILES['upload_file']["proper noun"])) {         $fileName = $_FILES["upload_file"]["proper name"];          $isValidFile = truthful;          // Validate if file already exists         if (file_exists($fileName)) {             echo "<span>File already exists.</bridge>";             $isValidFile = simulated;         }          // Validate file extension         $allowedFileType = array(             'jpg',             'jpeg',             'png'         );         $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));         if (! in_array($fileExtension, $allowedFileType)) {             echo "<span>File is not supported. Upload merely <b>" . implode(", ", $allowedFileType) . "</b> files.</span>";             $isValidFile = faux;         }          // Validate file size         if ($_FILES["upload_file"]["size"] > 200000) {             echo "<span>File is too large to upload.</bridge>";             $isValidFile = 0;         }          if ($isValidFile) {             move_uploaded_file($_FILES["upload_file"]["tmp_name"], $fileName);         }     } else {         echo "No files have been chosen.";     } } ?>        

Upload file to the server with database

This section gives a full-fledged PHP file upload example. It is with add, edit, preview, list images features. The add/edit allows users to choose an image file to upload to the server.

The home page displays a listing of uploaded images with edit, delete action controls. The edit screen volition bear witness the preview of the existing file.

PHP file upload and add a new row to the database

This lawmaking is for showing a HTML course with a file upload choice. This allows users to choose files to upload to the server.

The PHP code receives the uploaded file data in $_FILES. In this code, it checks for basic file validation to make sure of its uniqueness.

And then, it calls functions to upload and insert the file path to the database.

The uploadImage runs PHP move_upload_files() to put the uploaded file in a directory.

The insertImage calls database handlers to insert the uploaded path to the database.

image-upload-list-preview-edit/insert.php

                      <?php namespace Phppot;  use Phppot\DataSource; require_once __DIR__ . '/lib/ImageModel.php'; $imageModel = new ImageModel(); if (isset($_POST['send'])) {     if (file_exists('../uploads/' . $_FILES['image']['name'])) {         $fileName = $_FILES['prototype']['name'];         $_SESSION['message'] = $fileName . " file already exists.";     } else {         $result = $imageModel->uploadImage();         $id = $imageModel->insertImage($result);         if (! empty($id)) {             $_SESSION['message'] = "Image added to the server and database.";         } else {             $_SESSION['message'] = "Image upload incomplete.";         }     }     header('Location: index.php'); }  ?> <html> <head> <link href="assets/manner.css" rel="stylesheet" type="text/css" /> </head> <torso>  	<div grade="form-container"> 		<h1>Add new epitome</h1> 		<grade activeness="" method="post" proper name="frm-add together" 			enctype="multipart/form-information" onsubmit="return imageValidation()"> 			<div Grade="input-row"> 				<input type="file" name="image" id="input-file" course="input-file" 					have=".jpg,.jpeg,.png"> 			</div> 			<input type="submit" name="send" value="Submit" form="btn-link"> <span 				id="message"></span> 	 	</div>  	</form>  	<script src="https://lawmaking.jquery.com/jquery-iii.6.0.min.js" 		integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 		crossorigin="bearding"></script> 	<script src="assets/validate.js"></script> </body> </html>                  

php file upload form

List of uploaded images with edit, delete actions

This is an extension of a usual PHP file upload example. Information technology helps to build a file library interface in an application.

This page reads the uploaded images from the database using PHP.  The getAllImages function returns the image path data in an array format.

The list page iterates this assortment and lists out the result. And it links the records with the advisable edit, delete controls.

paradigm-upload-list-preview-edit/index.php

                      <?php namespace Phppot;  use Phppot\DataSource; require_once __DIR__ . '/lib/ImageModel.php'; $imageModel = new ImageModel(); ?> <html> <head> <title>Brandish all records from Database</title> <link href="assets/style.css" rel="stylesheet" type="text/css" /> </head> <trunk> 	<div course="image-datatable-container"> 		<a href="insert.php" class="btn-link">Add Image</a> 		<table class="epitome-datatable" width="100%">  			<tr> 				<th width="80%">Image</th> 				<th>Action</thursday>  			</tr>          <?php         $result = $imageModel->getAllImages();          ?>          <tr>         <?php         if (! empty($result)) {             foreach ($outcome equally $row) {                 ?>             <td><img src="<?php repeat $row["paradigm"]?>" 					class="contour-photograph" alt="photo"><?php echo $row["name"]?>             </td> 				<td><a href="update.php?id=<?php repeat $row['id']; ?>" 					class="btn-activity">Edit</a> <a 					onclick="confirmDelete(<?php repeat $row['id']; ?>)" 					class="btn-action">Delete</a></td> 			</tr>             <?php             }         }         ?>     </tabular array> 	</div> 	<script src="https://lawmaking.jquery.com/jquery-iii.6.0.min.js" 		integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 		crossorigin="anonymous"></script> 	<script type="text/javascript" src="assets/validate.js"></script> </body>  </html>                  

list uploaded files from server

Edit form with file preview

This shows an edit form with an uploaded file preview. It allows replacing the file by uploading a new one.

The grade action passes the id of the record to update the file path in the database.

The PHP code calls the updateImage with the upload consequence and the record id.

image-upload-listing-preview-edit/update.php

                      <?php namespace Phppot;  employ Phppot\DataSource; require_once __DIR__ . '/lib/ImageModel.php'; $imageModel = new ImageModel(); if (isset($_POST["submit"])) {     $outcome = $imageModel->uploadImage();     $id = $imageModel->updateImage($result, $_GET["id"]); } $result = $imageModel->selectImageById($_GET["id"]);  ?> <html> <caput> <link href="assets/fashion.css" rel="stylesheet" blazon="text/css" /> </head> <trunk> 	<div form="course-container"> 		<h1>View/Edit prototype</h1>  		<form action="?id=<?php repeat $result[0]['id']; ?>" method="post" 			name="frm-edit" enctype="multipart/course-data" 			onsubmit="return imageValidation()"> 			<div class="preview-container"> 				<img src="<?php repeat $result[0]["paradigm"]?>" class="img-preview" 					alt="photograph"> 				<div>Proper noun: <?php echo $consequence[0]["name"]?></div> 			</div> 			<div Class="input-row"> 				<input type="file" name="image" id="input-file" class="input-file" 					have=".jpg,.jpeg,.png" value=""> 			</div> 			<button type="submit" proper name="submit" course="btn-link">Save</button> 			<span id="bulletin"></span> 	 	</div> 	</class> 	<script src="https://code.jquery.com/jquery-3.half-dozen.0.min.js" 		integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" 		crossorigin="anonymous"></script> 	<script src="assets/validate.js"></script> </body> </html>                  

file edit form with preview

The delete activity is triggered later on user confirmation. Information technology removes the file path from the database.

delete.php

                      <?php namespace Phppot;  utilise Phppot\DataSource; require_once __DIR__ . '/lib/ImageModel.php'; $imageModel = new ImageModel(); $id=$_REQUEST['id']; $outcome = $imageModel->deleteImageById($id); header("Location: index.php"); ?>                  

PHP model class to upload file

It contains functions to upload files to a directory and to the database. The PHP file upload function sets a target to put the uploaded file.

Information technology processes the PHP $_FILES assortment to become the file information. Information technology prepares the database query by using the file parameter to perform read, write.

imageModel.php

                      <?php namespace Phppot;  employ Phppot\DataSource;  form ImageModel {      private $conn;      function __construct()     {         require_once 'DataSource.php';         $this->conn = new DataSource();     }      function getAllImages()     {         $sqlSelect = "SELECT * FROM tbl_image";         $event = $this->conn->select($sqlSelect);         return $result;     }      function uploadImage()     {         $imagePath = "uploads/" . $_FILES["image"]["name"];         $name = $_FILES["image"]["name"];         $outcome = move_uploaded_file($_FILES["image"]["tmp_name"], $imagePath);         $output = assortment(             $name,             $imagePath         );         return $output;     }      public function insertImage($imageData)     {         print_r($imageData);         $query = "INSERT INTO tbl_image(name,epitome) VALUES(?,?)";         $paramType = 'ss';          $paramValue = assortment(             $imageData[0],             $imageData[1]         );         $id = $this->conn->insert($query, $paramType, $paramValue);         return $id;     }      public function selectImageById($id)     {         $sql = "select * from tbl_image where id=? ";         $paramType = 'i';         $paramValue = array(             $id         );         $outcome = $this->conn->select($sql, $paramType, $paramValue);         return $result;     }      public function updateImage($imageData, $id)     {         $query = "UPDATE tbl_image Prepare proper noun=?, image=? WHERE id=?";         $paramType = 'ssi';         $paramValue = array(             $imageData[0],             $imageData[1],             $_GET["id"]         );         $id = $this->conn->execute($query, $paramType, $paramValue);         render $id;     }      /*      * public function execute($query, $paramType = "", $paramArray = array())      * {      * $id = $this->conn->prepare($query);      *      * if (! empty($paramType) && ! empty($paramArray)) {      * $this->bindQueryParams($id, $paramType, $paramArray);      * }      * $id->execute();      * }      */     function deleteImageById($id)     {         $query = "DELETE FROM tbl_image WHERE id=$id";         $result = $this->conn->select($query);         render $upshot;     } } ?>                  

Upload image equally a blob to the database

Though this example comes equally the last, I judge it will exist very useful for most of you readers.

Uploading the file as a hulk to the database helps to movement the file binary data to the target database. This instance achieves this with very few lines of code.

Uploading image file blob using database insert

This file receives the uploaded file from PHP $_FILES. Information technology extracts the file binary data by using PHP file_get_contents() function.

Then, it binds the file MIME type and the hulk to the prepared query statement.

The lawmaking specifies the parameter type as 'b' for the file blob data. First, information technology binds a Nil value for the hulk field.

So, it sends the file content using send_long_data() function. This office specifies the query parameter index and file blob to demark it to the statement.

file-blob-upload/alphabetize.php

<?php if (!empty($_POST["submit"])) {     if (is_uploaded_file($_FILES['userImage']['tmp_name'])) {         $conn = mysqli_connect('localhost', 'root', '', 'blog_eg');         $imgData = file_get_contents($_FILES['userImage']['tmp_name']);         $imageProperties = getimageSize($_FILES['userImage']['tmp_name']);         $goose egg = Nada;         $sql = "INSERT INTO tbl_image_data(image_type ,image_data) 	VALUES(?, ?)";         $stmt = $conn->set up($sql);         $stmt->bind_param("sb", $imageProperties['mime'], $cypher);                  $stmt->send_long_data(1, $imgData);                  $stmt->execute();         $currentId = $stmt->insert_id;              } } ?>  <html> <head> <link href="assets/style.css" rel="stylesheet" type="text/css" /> </caput> <trunk> 	<div class="form-container"> 		<h1>Upload Image Blob</h1>  		<form action="" method="postal service" 			proper name="frm-edit" enctype="multipart/form-information" > 			<?php if(!empty($currentId)) { ?> 			<div course="preview-container"> 				<img src="image-view.php?image_id=<?php echo $currentId; ?>" grade="img-preview" 					alt="photograph"> 			</div> 			<?php } ?> 			<div Class="input-row"> 				<input type="file" name="userImage" id="input-file" form="input-file" 					accept=".jpg,.jpeg,.png" value="" required> 			</div> 			<input type="submit" name="submit" form="btn-link" value="Salvage"> 			<span id="message"></span> 	 	</div> 	</form> </trunk> </html>        

This file is to read a blob from the database and show the preview. It will be specified in the <img> tag 'src' attribute with the appropriate image id.

file-blob-upload/image-view.php

<?php     $conn = mysqli_connect('localhost', 'root', '', 'blog_eg');     if(isset($_GET['image_id'])) {         $sql = "SELECT image_type,image_data FROM tbl_image_data WHERE id = ?";         $stmt = $conn->set up($sql);         $stmt->bind_param("i", $_GET['image_id']);         $stmt->execute();         $upshot = $stmt->get_result();         $row = $result->fetch_array(); 		 		header("Content-type: " . $row["image_type"]);         repeat $row["image_data"]; 	} 	mysqli_close($conn); ?>        

php file upload blob to server

Conclusion

Thus, nosotros have seen a detailed article to learn file upload. I swear nosotros have covered most of the examples on PHP file upload.

Nosotros saw code in all levels from simple to elaborate file upload components. I promise, this volition be helpful to know how to build this on your own.
Download

↑ Back to Top

berrymasul1939.blogspot.com

Source: https://phppot.com/php/php-file-upload/

0 Response to "Upload Image With Form Path to Mysql Database"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel