File Upload with PHP, AJAX, and jQuery: A Comprehensive Step-by-Step Guide
Here is a comprehensive guide, including code, for file upload with PHP, AJAX, and jQuery, along with validation to ensure the file meets certain criteria before proceeding with the upload.
Step 1: Create an HTML form (index.html):
<!DOCTYPE html> <html> <head> <title>File Upload Example with Validation</title> </head> <body> <h2>File Upload</h2> <form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="fileInput"> <input type="submit" value="Upload" id="uploadBtn"> </form> <div id="progress"></div> <div id="message"></div> <!-- Include jQuery --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function() { $("#uploadForm").on('submit', function(e) { e.preventDefault(); var formData = new FormData(this); var fileInput = $("#fileInput"); var fileSize = fileInput[0].files[0].size; // Get file size // File size validation (Max size: 5MB) var maxSize = 5 * 1024 * 1024; // 5MB in bytes if (fileSize > maxSize) { $("#message").text("File size exceeds the maximum allowed size (5MB)."); return; } // File type validation (Only allow JPG, JPEG, PNG, and PDF files) var fileType = fileInput[0].files[0].type.split('/')[1].toLowerCase(); if (!["jpg", "jpeg", "png", "pdf"].includes(fileType)) { $("#message").text("Invalid file type. Only JPG, JPEG, PNG, and PDF files are allowed."); return; } $("#progress").text("Uploading..."); $.ajax({ xhr: function() { var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener("progress", function(evt) { if (evt.lengthComputable) { var percentComplete = (evt.loaded / evt.total) * 100; $("#progress").text(percentComplete.toFixed(2) + '%'); } }, false); return xhr; }, type: 'POST', url: 'upload.php', data: formData, processData: false, contentType: false, success: function(data) { $("#progress").text("Upload Complete!"); $("#message").html(data); }, error: function() { $("#progress").text("Upload Failed!"); } }); }); }); </script> </body> </html>
Step 2: Create a PHP file to handle the file upload (upload.php):
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) { $targetDir = "uploads/"; // Directory to store uploaded files $targetFile = $targetDir . basename($_FILES['file']['name']); $fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION)); // File type validation (Only allow JPG, JPEG, PNG, and PDF files) if (!in_array($fileType, array('jpg', 'jpeg', 'png', 'pdf'))) { echo "<p>Invalid file type. Only JPG, JPEG, PNG, and PDF files are allowed.</p>"; exit; } // File size validation (Max size: 5MB) $maxSize = 5 * 1024 * 1024; // 5MB in bytes if ($_FILES['file']['size'] > $maxSize) { echo "<p>File size exceeds the maximum allowed size (5MB).</p>"; exit; } if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) { echo "<p>File uploaded successfully: " . basename($_FILES['file']['name']) . "</p>"; } else { echo "<p>Failed to upload file.</p>"; } } ?>
Make sure to create an "uploads" directory in the same folder where you have the upload.php file to store the uploaded files.
This comprehensive example includes both client-side and server-side validation. The client-side validation checks the file size and type before initiating the AJAX request, while the server-side validation ensures that only files with allowed file types (JPG, JPEG, PNG, and PDF) and sizes (up to 5MB) are accepted for upload.
Remember, this is a basic example for learning purposes. In a real-world application, you would need to adjust the validation rules and add additional security measures depending on your specific use case and requirements.