PHP Ajax File Upload Tutorial


Share:
Published By: Admin, Published On: Apr 21, 2021, Category: PHP

Hi Dev,

In this blog, I will give you how to upload file in php with ajax. In this tutorial PHP file uploading and storing tutorial with ajax and mysql database. In this tutorial, we will learn how to upload files and files in MySQL Database using ajax.

File Upload in php with ajax. I am going to show you about file upload in php using jquery ajax. this example will help you php upload file to database with jquery ajax. This article goes in detailed on how to upload and display file in php with ajax. Here, Creating a basic example of php file upload with preview using jquery ajax.

I created simple form with file input. So you have to simple select file and then it will upload in "files" directory of this folder. So you have to simple follow bellow step and get file upload in php ajax application.

Here, I will give you full example for simply file Upload using php jquery ajax as bellow.

Create Database

In this step you can create database `php_curd`.

Create `table_name` inside the database.

You can execute the following command to create the table columns to store the files in the database.

CREATE TABLE `user` (
    `id` int(11) NOT NULL,
    `file` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Database Configuration conn.php
<?php

    $servername = 'localhost';
    $username   = 'root';
    $password   = 'root';
    $dbname     = "php_curd";
    $conn       = mysqli_connect($servername,$username,$password,$dbname);
    
    if(!$conn){
        die('Could not Connect MySql Server:' .mysql_error());
    }

?>
index.php
    
<html>
<head>
    PHP AJAX file Upload Tutorial - MyWebtuts.com
    
    
    
</head>
<body class="bg-dark">
    

PHP 8 Ajax file Upload - MyWebtuts.com

No File
</body> </html>
upload.php
<?php

    include 'conn.php';
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '
'; } else { move_uploaded_file($_FILES['file']['tmp_name'], 'files/' . $_FILES['file']['name']); $targetPath = "files/".$_FILES['file']['name']; $q = "INSERT INTO `user`(`file`) VALUES ('{$targetPath}')"; $sql = mysqli_query($conn, $q); } ?>

Now we are ready to run our example so run bellow command for quick run:

php -S localhost:8000

Now you can open bellow URL on your browser:

http://localhost:8000

It will help you..

Share: