Home > Article > Backend Development > How Can You Validate File Size Before Uploading?
Besides ensuring that uploaded files meet specific file type requirements, you may also want to restrict file sizes to avoid bulky uploads.
Modern browsers provide the HTML5 File API, enabling you to check file size before submitting the form.
<code class="javascript">document.forms[0].addEventListener('submit', function(evt) { var file = document.getElementById('file').files[0]; if(file && file.size < 10485760) { // 10 MB (size is in bytes) //Submit form } else { //Prevent default and display error evt.preventDefault(); } }, false);</code>
Even with client-side checks, it's crucial to validate file sizes on the server to handle any client-side tampering. The PHP $_FILES array provides access to file size information.
<code class="php"><?php if(isset($_FILES['file'])) { if($_FILES['file']['size'] > 10485760) { // 10 MB (size is in bytes) // File too big } else { // File within size restrictions } } ?></code>
By implementing both client-side and server-side validation, you can ensure compliance with your desired file size limits and streamline the upload process for your users.
The above is the detailed content of How Can You Validate File Size Before Uploading?. For more information, please follow other related articles on the PHP Chinese website!