Is it possible to use JavaScript to validate file uploads before they are sent to the server in PHP?

Yes, it is possible to use JavaScript to validate file uploads before they are sent to the server in PHP. You can use JavaScript to check the file size, file type, and other criteria before allowing the file to be uploaded. This can help prevent unnecessary server requests and improve user experience.

// PHP code to handle file upload after JavaScript validation

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $file = $_FILES['file'];

    // Check if file was uploaded successfully
    if ($file['error'] === UPLOAD_ERR_OK) {
        // Process the file upload
        move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);
        echo 'File uploaded successfully!';
    } else {
        echo 'Error uploading file.';
    }
}