How can the PHP script be modified to provide better error handling and informative messages to users during the file upload process?

To provide better error handling and informative messages during the file upload process in PHP, you can use try-catch blocks to catch any exceptions that may occur and display relevant error messages to the user. Additionally, you can check for specific error codes returned by the file upload process and provide corresponding messages to the user.

<?php
// Check if file was uploaded without errors
if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    try {
        // Process file upload
        // Your file upload code here
        echo "File uploaded successfully!";
    } catch (Exception $e) {
        echo "An error occurred: " . $e->getMessage();
    }
} else {
    // Display error message based on error code
    switch ($_FILES['file']['error']) {
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            echo "File is too large.";
            break;
        case UPLOAD_ERR_PARTIAL:
            echo "File upload was only partially completed.";
            break;
        case UPLOAD_ERR_NO_FILE:
            echo "No file was uploaded.";
            break;
        case UPLOAD_ERR_NO_TMP_DIR:
            echo "Missing temporary folder.";
            break;
        case UPLOAD_ERR_CANT_WRITE:
            echo "Failed to write file to disk.";
            break;
        case UPLOAD_ERR_EXTENSION:
            echo "A PHP extension stopped the file upload.";
            break;
        default:
            echo "Unknown error occurred.";
            break;
    }
}
?>