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.

Читайте также:  Roadmap python backend разработчик

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:

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.

Источник

Upload and Store Image File in Database using PHP and MySQL

Server-side file upload can be easily implemented using PHP. There are various ways available to upload image to server and display images on the webpage. Generally, in a dynamic web application, the uploaded image is stored in a directory of the server and the file name is inserted in the database. Later, the images are retrieved from the server based on the file name stored in the database and display on the web page.

The image can be uploaded directly to the database without storing on the server. But it will increase the database size and web page load time. So, it’s always a good idea to upload images to the server and store file names in the database. In this tutorial, we will show you the entire process to upload and store the image file in MySQL database using PHP.

The example code demonstrates the process to implement the file upload functionality in the web application and the following functionality will be implemented.

  • HTML form to upload image.
  • Upload image to server using PHP.
  • Store file name in the database using PHP and MySQL.
  • Retrieve images from the database and display in the web page.

Create Datbase Table

To store the image file name a table need to be created in the database. The following SQL creates an images table with some basic fields in the MySQL database.

CREATE TABLE `images` ( `id` int(11) NOT NULL AUTO_INCREMENT, `file_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `uploaded_on` datetime NOT NULL, `status` enum('1','0') COLLATE utf8_unicode_ci NOT NULL DEFAULT '1', 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 MySQL database. Specify the database hostname ( $dbHost ), username ( $dbUsername ), password ( $dbPassword ), and name ( $dbName ) as per your MySQL 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);
>
?>

Upload Form HTML

Create an HTML form to allow the user to choose a file they want to upload. Make sure < form >tag contains the following attributes.

Also, make sure < input >tag contains type=»file» attribute.

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

php-upload-image-file-to-server-codexworld

The file upload form will be submitted to the upload.php file to upload image to the server.

Upload File to Server and Store in Database (upload.php)

The upload.php file handles the image upload functionality and shows the status message to the user.

  • Include the database configuration file to connect and select the MySQL database.
  • Get the file extension using pathinfo() function in PHP and validate the file format to check whether the user selects an image file.
  • Upload image to server using move_uploaded_file() function in PHP.
  • Insert image file name in the MySQL database using PHP.
  • Upload status will be shown to the user.
// Include the database configuration file
include 'dbConfig.php';
$statusMsg = '';

// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);

if(isset(
$_POST["submit"]) && !empty($_FILES["file"]["name"])) // Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf');
if(
in_array($fileType, $allowTypes)) // Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) // Insert image file name into database
$insert = $db->query("INSERT into images (file_name, uploaded_on) VALUES ('".$fileName."', NOW())");
if(
$insert) $statusMsg = "The file ".$fileName. " has been uploaded successfully.";
>else
$statusMsg = "File upload failed, please try again.";
>
>else
$statusMsg = "Sorry, there was an error uploading your file.";
>
>else
$statusMsg = 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.';
>
>else
$statusMsg = 'Please select a file to upload.';
>

// Display status message
echo $statusMsg;
?>

Display Images from Database

Now we will retrieve the uploaded images from the server based on the file names in the database and display images in the web page.

  • Include the database configuration file.
  • Fetch images from MySQL database using PHP.
  • List images from the uploads directory of the server.
// Include the database configuration file
include 'dbConfig.php';

// Get images from the database
$query = $db->query("SELECT * FROM images ORDER BY uploaded_on DESC");

if(
$query->num_rows > 0) while($row = $query->fetch_assoc()) $imageURL = 'uploads/'.$row["file_name"];
?> img src=" echo $imageURL; ?>" alt="" /> >
>else ?> p
>No image(s) found. p
> > ?>

upload-image-retrieve-from-database-php-mysql-codexworld

Conclusion

Here we have shown the most effective way to implement image upload functionality on the website. You can easily extend the file upload functionality as per your requirements. For providing the better user-interface you can integrate the Ajax File Upload functionality.

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

Источник

База данных фото с помощью HTML, PHP и MySQL

Есть два способа загрузки изображений: в базу данных или на сервер. В этой статье мы разберемся как с помощью HTML, PHP и MySQL создается база данных фото. Предполагается, что у вас есть базовые знания HTML, PHP и MySQL.

Три этапа загрузки изображения в базу данных

1. Создайте HTML-форму для загрузки.
2. Подключитесь к базе данных и сохраните изображения.
3. Отобразите изображения.

Шаг 1. Создайте HTML-форму

Создадим HTML-форму с методом post и сохраним ее в файле с именем upload.html .

Мы отправляем данные из этой HTML-формы в файл getdata.php , с помощью которого изображение будет сохранено в базе данных.

Шаг 2. Подключитесь к базе данных и сохраните изображение

Сначала нужно подключиться к базе данных. В примере мы используем БД «demo».

Чтобы сохранить изображение в базе, нужно использовать для столбца в таблице тип данных blob . MySQL использует BLOB для хранения двоичных данных. Вы можете использовать BLOB TINYBLOB, BLOB, MEDIUMBLOB или LONGBLOB в зависимости от размера загружаемого рисунка.

Шаг 3. Отображение сохраненных изображений из базы данных

Чтобы вывести изображения, нужно создать два файла. Это файл fetch_image.php.

Теперь мы хотим отобразить изображение — это делается с помощью файла display_image.php .

Три шага для загрузки изображения на сервер

1. Создайте HTML-форму для загрузки изображения.
2. Сохраните путь к базе данных и изображение на сервере.
3. Выведите изображение.

Шаг 1. Создайте HTML-форму

Вы можете использовать HTML-форму из предыдущего примера.

Шаг 2. Сохранение изображения на сервере

На этом этапе мы получаем изображение и сохраняем его в каталоге, а затем сохраняем путь к изображению и имя файла в базе данных. Это файл store_image.php.

Шаг 3. Вывод изображений

Чтобы вывести изображение, нужно получить из базы данных имя файла и путь к нему. Это файл fetch_image.php.

Таким образом можно загрузить изображение в базу данных с помощью HTML, PHP и MySQL.

Источник

Upload Image PHP MySQL – Uploading and Retrieving Images

upload image php mysql

So you are thinking how to upload images to your MySQL database? Here is the Upload Image PHP MySQL Tutorial, and in this tutorial, I am going to explain how we can upload or store images to MySQL database and then how we can retrieve the saved images.

  • 1 What We Need?
  • 2 Upload Image PHP MySQL Tutorial
    • 2.1 Creating Database
    • 2.2 Creating a PHP Project
    • 2.3 Defining Constants
    • 2.4 Connecting to Database
    • 2.5 Class to Perform Store and Retrieve Operation
    • 2.6 Converting String to Image
    • 2.7 Uploading and Retrieving Images
    • 2.8 Applying CSS to the Project
    • 3.1 Related

    What We Need?

    In this post I will be using.

    You can use other tools as well like wamp, lamp, and notepad++ or any IDE as well. The tools don’t matter the point is we will be using PHP and MySQL. So let’s begin.

    Upload Image PHP MySQL Tutorial

    Creating Database

    mysql database table

    • Here I will be storing the image directly to MySQL table. So the first thing we need is our table. And for creating the table you need to go to your PhpMyAdmin.
    • Start XAMPP server and go to localhost/phpmyadmin. Here you need to create a database. I have created a database named SimplifiedCoding.
    • Now inside this database we need a table as below.
    • For creating the above table you can use the following SQL.

    Источник

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