Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment Payment of ₹ requested by HONEY VIG. Click the link to pay securely via Razorpay: Make 5000 payment ⭐ If you would like to buy me a coffee, well thank you very much that is mega kind! : https://www.buymeacoffee.com/honeyvig
Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Tuesday, September 21, 2021

How to Upload Files on Server using Ajax in PHP 8?

 

Hello Friends,

This tutorial will provide example of how to upload files on server using ajax in php 8?. if you have question about PHP 8 File Upload using Ajax MySQL Database Example then I will give simple example with solution. you can see How to Upload file using ajax jQuery PHP 8 and MySQL. this example will help you PHP 8 Upload & Store File in MySQL Tutorial.

This article will give you simple example of How to Insert Files into a MySQL Database Using PHP 8

So, let's see bellow solution:

index.php
<!DOCTYPE html>
<html lang="en">
<head>
    <title>How to Upload Files on Server using Ajax in PHP 8?</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-12">
                <div class="card m-auto w-75">
                    <div class="card-header text-center text-white bg-dark">
                        <h4>How to Upload Files on Server using Ajax in PHP 8? - Tuts-Station.com</h4>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-success alert-dismissible" id="success" style="display: none;">
                            <button type="button" class="close" data-dismiss="alert">×</button>
                                File uploaded successfully
                        </div>
                        <form id="submitForm">
                            <div class="form-group">
                                <label><strong>Select File : </strong><span class="text-danger"> *</span></label>
                                <input type="file" class="form-control" name="file" id="file" multiple>
                             <span id="error" class="text-danger"></span><br>    
                            </div>
                            <div class="form-group d-flex justify-content-center">
                                <button type="submit" name="upload" class="btn btn-primary">Upload</button>
                            </div>  
                        </form>         
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $(document).ready(function(){
            $("input").prop('required',true);
            $('#file').change(function () {
                var ext = this.value.match(/\.(.+)$/)[1];
                    switch (ext) {
                        case 'txt':
                        case 'pdf':
                        case 'docx':
                        case 'csv':
                        case 'xlsx':
                            $('#error').text("");
                            $('button').attr('disabled', false);
                            break;
                    default:
                        $('#error').text("File must be of type txt,pdf,docx,csv,xlsx.");
                        $('button').attr('disabled', true);
                        this.value = '';
                }
            });
            $("#submitForm").on("submit", function(e){
                e.preventDefault();
                $.ajax({
                    url  :"store.php",
                    type :"POST",
                    cache:false,
                    contentType : false, // you can also use multipart/form-data replace of false
                    processData : false,
                    data: new FormData(this),
                    
                    success:function(response){
                      $("#success").show();
                      $("#success").fadeOut(2800);
                    }
                });
            });
        });
    </script>
</body>
</html>
store.php
<?php 

    if (isset($_FILES['file'])) {
        
        $file_name = $_FILES['file']['name'];    
        $file_size = $_FILES['file']['size'];    
        $file_tmp = $_FILES['file']['tmp_name'];     
        $file_type = $_FILES['file']['type'];        

        $servername = "localhost";
        $username = "root";
        $password = "";
        $dbname = "tests";

        $conn = mysqli_connect($servername, $username, $password, $dbname);

        if (!$conn) {
            die("connection failed:" .mysqli_connect_error());
            echo "connection successfull";
        }
            
        $sql="INSERT INTO posts(file) VALUES('$file_name')";
            
        if ($conn->query($sql)===TRUE) {
            echo " ";
        }else{
            echo "<h5 class='alert alert-primary'>Error :".$sql."<br>".$conn->error."</h5>";
        }
            
        if (move_uploaded_file($file_tmp ,"uploads/".$file_name)) {
            echo "<h5 class='alert alert-primary'>File inserted Successfully!</h5>";
        }else{
            echo "<h5 class='alert alert-primary'>File Was Not inserted!</h5>";
        }
    }
?>

Cookieless Alternative To Embed HTML, CSS And JS Code Snippets

 Embedding code examples with third-party scripts often leads to tracking or cookies. We always wanted to have a simple website with a good UX, so setting cookies for no reason wasn’t an option for us. 

When we implement websites today, we are confronted by a lot of things we need to take care of. Ideally, we want to have a fast, secure, accessible, and fair website. At the same time, we want to have an interactive website with comments, polls, videos, code examples, and many more.

Together with a friend, I launched a tech blog last year and we ran exactly into that issue. We wanted to have a simple solution to embedding HTML, CSS, and JavaScript code examples but existing solutions often include tracking, cookies, a ton of features or bad performance. After some research, we realized that we had to build an alternative. Indiapen

Indiepen is a privacy-friendly, lightweight, and accessible solution to embed code examples. In fact, we don’t set any cookies or tracking!

Get Started

Indiepen can preview every website that follows a very simple convention. You need to provide a website with the following file structure:

.
├── index.html
├── main.js
└── styles.css

Deploy the code example with your favorite hosting provider (e.g. GitHub Pages, Netlify, or Vercel) and copy the URL. After that, go to our start page and use the code snippet generator.

The generated code looks like this:

<iframe class="indiepen"
  src="https://indiepen.tech/embed/?url=https%3A%2F%2Findiepen.tech%2Fexample%2F&tab=result"
  style="width: 100%; overflow: hidden; display: block; border: 0;"
  title="Indiepen Embed"
  loading="lazy"
  width="100%"
  height="450">
</iframe>

You can now use the code snippet and integrate it on your website. That’s it! You should now see your code example with an editor to discover the code.

Under The Hood

It sounds a bit strange nowadays but we haven’t used any JavaScript framework like React or Vue.js. It’s pure HTML, CSS and JavaScript with some help from Lea Verou’s Prism.js for syntax highlighting. Those libraries are very helpful to implement and maintain complex web applications but in our case, we just have three files we need to fetch and pass onto Prism.js.

Additionally, we have three buttons in the upper right corner to switch between the HTML, CSS, and JavaScript views. By introducing a UI framework, we couldn’t deliver a lightweight solution with less than 20 kb in size. For us, it was good learning, that UI libraries are important in our day-to-day business but we should carefully consider them and don’t forget the good old vanilla JavaScript.

 

Final Words 

Indiepen is open-source project and we are very excited to share our ideas with you. We would love to get feedback and have discussions about a fair web. Get in touch with me on Twitter or check out the project on GitHub.

Last but not least, I’d like to mention that Indiepen has a limited scope and we want to keep it simple by design. If you need to deal with more complex code examples, preprocessors for CSS or JavaScript, or you want to benefit from a platform to share your ideas, then please consider more sophisticated solutions like CodePen or JSFiddle.