File Upload in PHP MySQL database

PHP file/image upload into MySQL database with validation example; This tutorial will show you how to upload image/file in mysql database and directory using php.

And as well as you will learn how to validate file/image before uploading the file to the php server.

When you work with PHP and need to upload several types of files like images, zip files, PDF files, document files, text files, video files, audios files on a remote web server.

How to Upload File/Image in MySQL Database using PHP

  • Step 1 – Create Database and Table
  • Step 2 – Create PHP App
  • Step 3 – Connect App to Database
  • Step 4 – Create Image Upload Form
  • Step 5 – Create uplaod.php file

Step 1 – Create Database and Table

Execute the following queries to create database and table:

CREATE DATABASE demos;
 
CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `file` varchar(255) NOT NULL
  `type` varchar(255) NOT NULL
  `size` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Step 2 – Create PHP App

Visit your server directory; if you use xampp; So visit xampp/htdocs directory. And create a new directory which name file-upload-app.

Step 3 – Connect App to Database

Connect your app to database; so visit your app root directory and create db.js file and the following code into it:

<?php
    $host='localhost';
    $username='root';
    $password='';
    $dbname = "demos";
    $conn=mysqli_connect($host,$username,$password,"$dbname");
    if(!$conn)
        {
          die('Could not Connect MySql Server:' .mysql_error());
        }
?>

Step 4 – Create File/Image Upload Form

Create file/image upload html form; so visit your app root directory and create index.php file and add the following code into it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP File Upload Example - CodeOne.com</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <h2>PHP Upload File</h2>
        <label for="file_name">Filename:</label>
        <input type="file" name="anyfile" id="anyfile">
        <input type="submit" name="submit" value="Upload">
        <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
    </form>
</body>
</html>

Step 5 – Create uplaod.php file

Create one file name upload.php file and add the below code into your upload.php file. The following PHP code uploads the files from the web server with validation. Here also we will validate the size of the file.

<?php
include_once 'db.php';
// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["anyfile"]) && $_FILES["anyfile"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["anyfile"]["name"];
        $filetype = $_FILES["anyfile"]["type"];
        $filesize = $_FILES["anyfile"]["size"];
     
        // Validate file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
     
        // Validate file size - 10MB maximum
        $maxsize = 10 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
     
        // Validate type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                if(move_uploaded_file($_FILES["anyfile"]["tmp_name"], "upload/" . $filename)){
 
                    $sql="INSERT INTO images(file,type,size) VALUES('$filename','$filetype','$filesize')";
                     
                    mysqli_query($conn,$sql);
 
                    echo "Your file was uploaded successfully.";
                }else{
 
                   echo "File is not uploaded";
                }
                 
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["anyfile"]["error"];
    }
}
?>

Conclusion

PHP MySQL file upload tutorial, you have learned how to upload files on web server using PHP. You also learned how you can validate the size and type of files.

Leave a Reply

Your email address will not be published.