What role does JavaScript play in validating file sizes before uploading in PHP, and how effective is it in preventing traffic consumption?

JavaScript can be used to validate file sizes before uploading in PHP by checking the size of the file selected by the user before it is sent to the server. This can help prevent unnecessary traffic consumption by restricting the upload of large files that may exceed server limits. By implementing client-side validation with JavaScript, users can be notified of any size restrictions before attempting to upload a file, improving the user experience.

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $maxFileSize = 5 * 1024 * 1024; // 5MB limit

    if ($_FILES['file']['size'] > $maxFileSize) {
        echo 'File size exceeds limit. Please upload a smaller file.';
    } else {
        // Process file upload
    }
}
?>