How can JavaScript be utilized to store a file name in a variable before form submission in PHP?

To store a file name in a variable before form submission in PHP, you can use JavaScript to capture the file name from the file input field and store it in a hidden input field. This way, when the form is submitted, the file name will be included in the form data and can be accessed in the PHP script.

<form method="post" enctype="multipart/form-data" id="myForm">
    <input type="file" id="fileInput" name="fileInput">
    <input type="hidden" id="fileName" name="fileName">
    <button type="submit">Submit</button>
</form>

<script>
    document.getElementById('myForm').addEventListener('submit', function() {
        var fileName = document.getElementById('fileInput').value.split('\\').pop();
        document.getElementById('fileName').value = fileName;
    });
</script>