What are best practices for handling large file uploads in PHP to avoid issues like interrupting uploads?

When handling large file uploads in PHP, it is important to adjust the PHP configuration settings to allow for larger file uploads and longer execution times. Additionally, using AJAX to upload files asynchronously can help prevent interruptions in the upload process. Implementing a progress bar can also provide feedback to the user and improve the overall user experience.

// Adjust PHP configuration settings
ini_set('upload_max_filesize', '20M');
ini_set('post_max_size', '20M');
ini_set('max_execution_time', 300);

// Use AJAX for asynchronous file uploads
// HTML form
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

// JavaScript code
$(document).ready(function(){
    $('#uploadForm').submit(function(e){
        e.preventDefault();
        var formData = new FormData($(this)[0]);
        
        $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response){
                // Handle success
            },
            error: function(){
                // Handle error
            }
        });
    });
});

// Implement a progress bar
// HTML
<div id="progressBar"></div>

// JavaScript code
xhr.upload.addEventListener('progress', function(event) {
    if (event.lengthComputable) {
        var percentComplete = event.loaded / event.total;
        $('#progressBar').css('width', percentComplete * 100 + '%');
    }
});