PHP File Upload Example — Tutsmake.com

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

  • 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:

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:

       

PHP Upload File

Note: Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.

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.

 "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:

Читайте также:  Css изменить адрес ссылки

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.

Источник

Store and Retrieve Image from MySQL Database using PHP

Generally, when we upload image file in PHP, the uploaded image is stored in a directory of the server and the respective image name is stored in the database. At the time of display, the file is retrieved from the server and the image is rendered on the web page. But, if you don’t want to consume the space of the server, the file can be stored in the database only. You can upload an image without storing the file physically on the server using the MySQL database. It’s very easy to store and retrieve images from the database using PHP and MySQL.

If you’re concerned about the server space and need free space on your server, you can insert the image file directly in the database without uploading it to the directory of the server. This procedure helps to optimize the server space because the image file content is stored in the database rather than the server. In this tutorial, we will show you how to store image files into the MySQL database and retrieve images from the database using PHP.

Before getting started to integrate file upload with the database, take a look at the file structure.

store_retrieve_image_from_database/ ├── dbConfig.php ├── index.php ├── upload.php ├── view.php └── css/ └── style.css

Insert Image File in MySQL

MySQL has a BLOB (binary large object) data type that can hold a large amount of binary data. The BLOB data type is perfect for storing image data in the database. In MySQL, four BLOB types are available – TINYBLOB, BLOB, MEDIUMBLOB, and LONGBLOB. The LONGBLOB data type is perfect to store the image file data.

Create Database Table

To store the file content, a table is required in the database. The following SQL creates an images table with the LONGBLOB data type field in the MySQL database.

CREATE TABLE `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `image` longblob NOT NULL, `created` datetime NOT NULL DEFAULT current_timestamp(), PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php)

The dbConfig.php file is used to connect and select the database. Specify the database host ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as per your MySQL database credentials.

// Database configuration 
$dbHost = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName = "codexworld";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) <
die(
"Connection failed: " . $db->connect_error);
>

Image Upload Form

Create an HTML form with a file input field to select an image file for upload. Make sure the < form >tag contains the following attributes.

form action="upload.php" method="post" enctype="multipart/form-data"> label>Select Image File: label> input type="file" name="image"> input type="submit" name="submit" value="Upload"> form>

Store Image File in Database (upload.php)

The upload.php file handles the image upload and database insertion process.

  • Check whether the user selects an image file to upload.
  • Retrieve the content of image file by the tmp_name using PHP file_get_contents() function.
  • Insert the binary content of the image in the database using PHP and MySQL.
  • Show the image uploading status to the user.
// Include the database configuration file 
require_once 'dbConfig.php';

// If file upload form is submitted
$status = $statusMsg = '';
if(isset(
$_POST["submit"])) <
$status = 'error';
if(!empty(
$_FILES["image"]["name"])) <
// Get file info
$fileName = basename($_FILES["image"]["name"]);
$fileType = pathinfo($fileName, PATHINFO_EXTENSION);

// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif');
if(
in_array($fileType, $allowTypes)) <
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));

// Insert image content into database
$insert = $db->query("INSERT into images (image, created) VALUES ('$imgContent', NOW())");

if(
$insert) <
$status = 'success';
$statusMsg = "File uploaded successfully.";
>else <
$statusMsg = "File upload failed, please try again.";
>
>else <
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
>
>else <
$statusMsg = 'Please select an image file to upload.';
>
>

// Display status message
echo $statusMsg;
?>

Retrieve image from database (view.php)

In the view.php file, we will retrieve the image content from the MySQL database and list them on the web page.

  • The data, charset, and base64 parameters in the src attribute, are used to display image BLOB from MySQL database.
// Include the database configuration file 
require_once 'dbConfig.php';

// Get image data from database
$result = $db->query("SELECT image FROM images ORDER BY id DESC");
?> if($result->num_rows > 0) ?>
div class="gallery">

while($row = $result->fetch_assoc()) ?>
img src="data:image/jpg;charset=utf8;base64, echo base64_encode($row['image']); ?>" />
> ?>
div
>

>else ?>
p class="status error">
Image(s) not found. p
>

> ?>

Conclusion

This tutorial helps you to integrate file upload functionality without storing files on the server. You can use this example script to upload & store images in the database, and fetch images from the database, and display them on the webpage using PHP and MySQL. To make the image upload process user-friendly, use jQuery to upload files with progress bar using Ajax and PHP.

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Источник

Uploading image in database php

  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?

PHP Date Based

  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?

PHP String Based

  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?

PHP Class Based

PHP JSON Based

PHP File Systems Based

Источник

Оцените статью