0

I am working on PHP form which allows user to upload files to a server directory.

All the following code is in a single file named upload.php

The following code uses a standard HTML Form, which first checks the size of the file the user selects using JAVASCRIPT. If the file size is above limit (1 MB) it is supposed to STOP the upload, show an ALERT message ("File too large. Try uploading smaller size."), and then stop processing everything & redirect again to the blank form page upload.php

<form action="" method="post" enctype="multipart/form-data">
  <table border="1px">
    <tr><td><input type="file" name="image" id="imgfile"></td></tr>
    <tr><td> <input type="submit" value="upload" name="Submit"></td></tr>
  </table>
</form>
<script>
document.forms[0].addEventListener('submit', function( evt ) {
    var file = document.getElementById('imgfile').files[0];

    if(file && file.size < 1000000) { // 1 MB (this size is in bytes)
        alert("File within limit. Proceeding with upload.");
    } else {
        alert("File too large. Try again by uploading smaller size.");
        window.location.href ="https://example.com/upload.php";
    }
}, false);
</script>

<?php
if(isset($_POST['Submit']))
{
    
    // PHP Server side Code to process submitted file
    // Here also I'm checking the file size at server end
}

The code works fine till the ALERT message which is also shown correctly when a large-sized file is selected by the user. However, the problem is that AFTER the alert is shown & user clicks OK, the upload still happens.

I am not very good in JavaScript, so want to know what changes are needed to stop the processing & redirect to happen correctly.

Using https://stackoverflow.com/a/19825478/6337701, I've tried using both window.location & window.location.href, but none are working.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Aquaholic
  • 863
  • 9
  • 25
  • I pressed enter too quickly. Please see my answer – mplungjan Mar 28 '23 at 13:07
  • 1
    Don't use alerts. They're a terrible UX. Use in-page messaging or custom modals. _Especially_ for situations which shouldn't require user input. You're making their life harder. – isherwood Mar 28 '23 at 13:08
  • You do not cancel the form submission. https://stackoverflow.com/questions/53314836/stop-form-submission-when-using-javascript – epascarello Mar 28 '23 at 13:12

1 Answers1

0

Add a preventDefault

else {
  alert("File too large. Try again by uploading smaller size."); 
  evt.preventDefault();          
  window.location.href ="https://example.com/upload.php";
}

You many not even need window.location.href ="https://example.com/upload.php";

mplungjan
  • 169,008
  • 28
  • 173
  • 236