How to upload large file using PHP and ajax

When uploading large files in PHP using AJAX, you may encounter some issues related to the maximum file size allowed by the server and the execution time limit. To handle this, you can follow these steps:

Set the maximum file size in your PHP configuration file (php.ini) to a value that allows for the size of your large files. For example, you can set the "upload_max_filesize" and "post_max_size" directives to a larger value. You can check the current value by running the "phpinfo()" function.

Set the maximum execution time in your PHP configuration file (php.ini) to a value that allows for the time it takes to upload large files. For example, you can set the "max_execution_time" directive to a larger value.

Create a form in your HTML page that allows users to select the large file they want to upload. This form should have an input field of type "file".

Add a JavaScript function to your HTML page that handles the file upload using AJAX. This function should listen for the "change" event of the input field, and send the file to the server using the XMLHttpRequest object.

In your PHP script, use the "move_uploaded_file" function to move the uploaded file to a temporary directory on the server.

Send a response back to the JavaScript function indicating the status of the upload.

Here is a sample code for uploading a large file using AJAX:

HTML form:

<form enctype="multipart/form-data">
    <input type="file" name="file" id="file">
    <button type="button" onclick="uploadFile()">Upload</button>
</form>

JavaScript function:

function uploadFile() {
    var file = document.getElementById("file").files[0];
    var formData = new FormData();
    formData.append("file", file);
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "upload.php", true);
    xhr.upload.onprogress = function(event) {
        var percent = (event.loaded / event.total) * 100;
        console.log(percent + "% uploaded...");
    }
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            console.log(xhr.responseText);
        }
    }
    xhr.send(formData);
}

PHP script:

<?php
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tempFile = $_FILES["file"]["tmp_name"];
    $targetFile = "uploads/" . $_FILES["file"]["name"];
    move_uploaded_file($tempFile, $targetFile);
    echo "File uploaded successfully.";
} else {
    echo "Error uploading file.";
}
?>

This is just a basic example, and you can customize it according to your needs.

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...