PHP 8 Upload & Store File/Image in MySQL Database Tutorial

03-Apr-2023

.

Admin

PHP 8 Upload & Store File/Image in MySQL Database Tutorial

Hi Dev,

In this blog, I will give you how to upload image in php 8 using mysql database. In this tutorial PHP 8 file uploading and storing tutorial. In this tutorial, we will learn how to upload files and images in MySQL Database. and how to implement file upload validation before sending it to a web server.

Image Upload in php 8 I am going to show you about image upload in php 8. this example will help you php 8 upload image to database. This article goes in detailed on how to upload and display image in php 8. Here, Creating a basic example of php 8 image upload with preview.

I created simple form with file input. So you have to simple select image and then it will upload in "images" directory of public folder. So you have to simple follow bellow step and get image upload in php 8 application.

Here, I will give you full example for simply Image Upload using php 8 as bellow.

Create Database


In this step you can create database `php_crud`.

Create `table_name` inside the database.

You can execute the following command to create the table columns to store the images in the database.

CREATE TABLE `user` (

`id` int(11) NOT NULL,

`image` varchar(255) NOT NULL

) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Database Configuration

config.php

<?php

$hostname = "localhost";

$username = "root";

$password = "root";

try {

$conn = new PDO("mysql:host=$hostname;dbname=php_crud", $username, $password);

// set the PDO error mode to exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

//echo "Database connected successfully";

} catch(PDOException $e) {

echo "Database connection failed: " . $e->getMessage();

}

?>

index.php

<?php include("store.php"); ?>

<!doctype html>

<html lang="en">

<head>

<title>PHP 8 Image Upload Example</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

</head>

<body>

<div class="container mt-5">

<div class="row">

<div class="col-md-8 offset-2">

<div class="card">

<div class="card-header">

<h3 class="text-center">PHP 8 Image Upload Example</h3>

</div>

<div class="card-body">

<!-- Display response messages -->

<?php if(!empty($resMessage)) {?>

<div class="alert <?php echo $resMessage['status']?>">

<?php echo $resMessage['message']?>

</div>

<?php }?>

<form action="" method="post" enctype="multipart/form-data" class="mb-3">

<div class="user-image mb-3 text-center">

<div style="width: 100px; height: 100px; overflow: hidden; background: #cccccc; margin: 0 auto">

<img src="..." class="figure-img img-fluid rounded" id="imgPlaceholder" alt="">

</div>

</div>

<div class="custom-file">

<input type="file" name="fileUpload" class="custom-file-input" id="chooseFile">

<label class="custom-file-label" for="chooseFile">Select file</label>

</div>

<button type="submit" name="submit" class="btn btn-primary btn-block mt-4">

Upload File

</button>

</form>

</div>

</div>

</div>

</div>

</div>

<!-- jQuery -->

<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>

<script>

function readURL(input) {

if (input.files && input.files[0]) {

var reader = new FileReader();

reader.onload = function (e) {

$('#imgPlaceholder').attr('src', e.target.result);

}

reader.readAsDataURL(input.files[0]); // convert to base64 string

}

}

$("#chooseFile").change(function () {

readURL(this);

});

</script>

</body>

</html>

store.php

<?php

// Database connection

include("config.php");

if(isset($_POST["submit"])) {

// Set image placement folder

$target_dir = "images/";

// Get file path

$target_file = $target_dir . basename($_FILES["fileUpload"]["name"]);

// Get file extension

$imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

// Allowed file types

$allowd_file_ext = array("jpg", "jpeg", "png");

if (!file_exists($_FILES["fileUpload"]["tmp_name"])) {

$resMessage = array(

"status" => "alert-danger",

"message" => "Select image to upload."

);

} else if (!in_array($imageExt, $allowd_file_ext)) {

$resMessage = array(

"status" => "alert-danger",

"message" => "Allowed file formats .jpg, .jpeg and .png."

);

} else if ($_FILES["fileUpload"]["size"] > 2097152) {

$resMessage = array(

"status" => "alert-danger",

"message" => "File is too large. File size should be less than 2 megabytes."

);

} else if (file_exists($target_file)) {

$resMessage = array(

"status" => "alert-danger",

"message" => "File already exists."

);

} else {

if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) {

$sql = "INSERT INTO user (image) VALUES ('$target_file')";

$stmt = $conn->prepare($sql);

if($stmt->execute()){

$resMessage = array(

"status" => "alert-success",

"message" => "Image uploaded successfully."

);

}

} else {

$resMessage = array(

"status" => "alert-danger",

"message" => "Image coudn't be uploaded."

);

}

}

}

?>

Now we are ready to run our example so run bellow command for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000

It will help you....

#PHP