Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to Upload Image FIle into Database in PHP and MySQL

How to Upload Image FIle into Database in PHP and MySQL

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

And as well as you will learn how to validate a 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, audio files on a remote web server.

How to Upload and Store Image File in database using PHP and MySQL

Use the following steps to upload the image file with MySQL database in PHP:

  • Step 1 – Create a 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 a Database and Table

Execute the following queries to create a 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 - Tutsmake.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"];
    }
}
?>

Know About – Upload.php File Code

Here, if any you uploaded a file using this field name anyfile, we can obtains its details like the name, type, size, temporary name or any error occurred while attempting the upload via the $_FILES[“anyfile”] associative array, like this:

1). $_FILES[“anyfile”][“name”] — This array value specifies the original name of the file, including the file extension. It doesn’t include the file path.

2). $_FILES[“anyfile”][“type”] — This array value specifies the MIME type of the file.

3). $_FILES[“anyfile”][“size”] — This array value specifies the file size, in bytes.

4). $_FILES[“anyfile”][“tmp_name”] — This array value specifies the temporary name including full path that is assigned to the file once it has been uploaded to the server.

5). $_FILES[“anyfile”][“error”] — This array value specifies error or status code associated with the file upload, e.g. it will be 0, if there is no error.

Conclusion

PHP MySQL file upload example 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.

Recommended PHP Tutorials

RELATED ARTICLES

Most Popular

Recent Comments