- PHP 8 Upload & Store File/Image in MySQL Tutorial
- PHP 8 File Upload Tutorial Example
- Table of Contents
- Getting Started
- Create Database & Table
- Create File Uploading Form
- Display Image Preview
- Database Configuration
- File/Image Upload Validation in PHP 8
- Complete PHP 8 File Upload Example
- Conclusion
- File Upload, View and Download using PHP and MySQL
- How to Upload, View & Download File in PHP & MySQL?
- Create MySQL Database:
- dbconnect.php
- index.php
- uploads.php
PHP 8 Upload & Store File/Image in MySQL Tutorial
This is a step by step 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.
The Internet has never been a secure place; an army of malicious hackers may take advantage of your code that can bring severe damages to your php application.
Before uploading the file to the server, we must make sure the necessary file validation is done correctly. If we do not consider security factors, we might get into trouble.
PHP 8 File Upload Tutorial Example
- Display image preview before uploading
- Place all the uploaded images in a specific folder
- Store images path in the MySQL database
Along with that we will also cover the following image validation using PHP 8:
- Check if the real image is uploaded
- Allow only specific file extension such as .jpg, .jpeg or .png
- Make sure file size should not exceed 2MB
- Check if the file already exists
Table of Contents
Getting Started
Start MAMP or XAMPP, create the following folder and file structure in htdocs directory.
\-- php-file-upload |-- config |--- database.php |-- img_dir |--- image-1 |--- image-2 |-- file-upload.php |-- index.php
Create Database & Table
Create database `database_name` .
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, `file_path` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Create File Uploading Form
Create an HTML form that permits our users to select the image from their local device the same image which they want to store onto the server.
The input type should be set to file along with the name property.
Also, define the method=”post” and enctype=”multipart/form-data” tags.
form action="" method="post" enctype="multipart/form-data" class="mb-3"> h3 class="text-center mb-5">Upload File in PHP 8h3> 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 filelabel> div> button type="submit" name="submit" class="btn btn-primary btn-block mt-4"> Upload File button>
Display Image Preview
You can show image preview before uploading it to the server with the help of jQuery.
Import jQuery CDN link before the closing body tag.
script src="https://code.jquery.com/jquery-3.5.1.slim.min.js">script>
We have already declared the image tag with the blank src=”” tag.
img src=". " id="imgPlaceholder" alt="">
The following function converts the image string and places the base64 url in the HTML img tag when the user selects the image.
Place the following code right after the jQuery CDN script tag.
script> function readURL(input) if (input.files && input.files[0]) var reader = new FileReader(); reader.onload = function (e) $('#imgPlaceholder').attr('src', e.target.result); > // base64 string conversion reader.readAsDataURL(input.files[0]); > > $("#chooseFile").change(function () readURL(this); >); /script>
Database Configuration
Add following code in config/database.php file to make the PHP connection with MySQL database using PDO method.
// config/database.php $hostname = "localhost"; $username = "root"; $password = ""; 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(); > ?>
File/Image Upload Validation in PHP 8
Let us add our first validation with the help of the file_exists() PHP method. Display error message to the user if he does not select any image.
To address the errors, we set up a $resMessage array with status and message properties. We will display the messages to the user based on the response on the front-end.
if (!file_exists($_FILES["fileUpload"]["tmp_name"])) $resMessage = array( "status" => "alert-danger", "message" => "Select image to upload." ); >
The following code applies the validation that allows specific file type such as .jpg, jpeg and .png to be uploaded on the server. You won’t be allowed other file types, and will be displayed error message if you do so.
// Get file extension $imageExt = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); // Allowed file types $allowd_file_ext = array("jpg", "jpeg", "png"); else if (!in_array($imageExt, $allowd_file_ext)) $resMessage = array( "status" => "alert-danger", "message" => "Allowed file formats .jpg, .jpeg and .png." ); >
Set up image file size limit using the following code. A user can not allow more than 2MB size of image to upload.
else if ($_FILES["fileUpload"]["size"] > 2097152) $resMessage=array("status"=> "alert-danger", "message"=> "File is too large. File size should be less than 2 megabytes." ); >
The given below code checks if the current file is already uploaded.
else if (file_exists($target_file)) $resMessage = array( "status" => "alert-danger", "message" => "File already exists." ); >
Create img_dir folder in the root of your PHP upload file project, here we will store all the uploaded images.
// Database connection include("config/database.php"); if(isset($_POST["submit"])) // Set image placement folder $target_dir = "img_dir/"; // Get file path $target_file = $target_dir . basename($_FILES["fileUpload"]["name"]); if (!file_exists($_FILES["fileUpload"]["tmp_name"])) // Validation goes here > else if (move_uploaded_file($_FILES["fileUpload"]["tmp_name"], $target_file)) $sql = "INSERT INTO user (file_path) 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." ); > > > ?>
Complete PHP 8 File Upload Example
Complete PHP file upload code example can be found in the file-upload.php file.
// file-upload.php // Database connection include("config/database.php"); if(isset($_POST["submit"])) // Set image placement folder $target_dir = "img_dir/"; // 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 (file_path) 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." ); > > > ?>
Include the file-upload.php in the index.html file here we have defined the file upload form along with the message array.
include("file-upload.php"); ?> doctype html> html lang="en"> head> 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"> title>PHP 8 Image Upload Exampletitle> style> .container < max-width: 450px; >style> head> body> div class="container mt-5"> form action="" method="post" enctype="multipart/form-data" class="mb-3"> h3 class="text-center mb-5">Upload File in PHPh3> 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 filelabel> div> button type="submit" name="submit" class="btn btn-primary btn-block mt-4"> Upload File button> form> if(!empty($resMessage)) ?> div class="alert echo $resMessage['status']?>"> echo $resMessage['message']?> div> >?> div> 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>
Conclusion
We have completed the PHP 8 File Upload tutorial, and we learned how to upload and store image using PHP in MySQL database. I hope you liked this tutorial.
The complete code of this tutorial can be found on GitHub.
A Full-stack developer with a passion to solve real world problems through functional programming.
File Upload, View and Download using PHP and MySQL
Hi! In this tutorial let me show you about upload, view and download file in php and mysql. The file uploading process is similar to what we have discussed here, but this php script not only uploads file to the server but also stores the file path and its created date in mysql database. Apart from uploading file, it also gives you the option to view file on browser and download it from server.
With PHP you can practically upload any type of files and the file uploading script I have shared below will work for all file types like PDF, Document, Images, MP3, Videos, Zip archives etc. Just include those file extensions in the filtering process ( $allowed array) and you will be able to upload them.
How to Upload, View & Download File in PHP & MySQL?
Let’s move on to the coding part. First you should create mysql database to store file details.
Create MySQL Database:
CREATE DATABASE `demo` ; Use `demo`; CREATE TABLE IF NOT EXISTS `tbl_files` ( `id` int(9) NOT NULL AUTO_INCREMENT, `filename` varchar(255) NOT NULL, `created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;
Next is the database connectivity script that establishes connection to mysql database from php.
dbconnect.php
Then create index.php — this is the main file containing user interface. It has an upload form and a html table to display the list of uploaded files from database along with ‘View’ & ‘Download’ links for them.
index.php
# File Name View Download ?> " target="_blank">View " download>Download
Note: This demo uses twitter bootstrap for css stylesheet.
Running index.php will generate a page with upload form and table with files details similar to this. Users can either click on ‘View’ link to view the files on browser or on ‘Download’ to download the files from server.
Finally there is ‘uploads.php’ file which will be executed when the form is submitted to upload the selected file. Here is where we actually upload the file to the server from the client machine and save its name and uploaded date into the database.
uploads.php
0) < $row = mysqli_fetch_array($result); $filename = ($row['id']+1) . '-' . $filename; >else $filename = '1' . '-' . $filename; //set target directory $path = 'uploads/'; $created = @date('Y-m-d H:i:s'); move_uploaded_file($_FILES['file1']['tmp_name'],($path . $filename)); // insert file details into database $sql = "INSERT INTO tbl_files(filename, created) VALUES('$filename', '$created')"; mysqli_query($con, $sql); header("Location: index.php?st=success"); > else < header("Location: index.php?st=error"); >> else header("Location: index.php"); > ?>
This script upload file from local machine to server and stores its details into database and redirects to index.php. If everything goes right you will be able to see success message on completion.
If there’s any error you will be notified about it.
So we have seen about file upload and to view and download them using php and mysql database. If you want you can set the file size limit or restrict users to upload only pdf or images etc.