How Can You Validate File Size Before Uploading?

DDD
Release: 2024-10-26 10:14:02
Original
822 people have browsed it

How Can You Validate File Size Before Uploading?

Check File Size before Upload

Besides ensuring that uploaded files meet specific file type requirements, you may also want to restrict file sizes to avoid bulky uploads.

Client-Side Validation

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 &amp;&amp; file.size < 10485760) { // 10 MB (size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);</code>
Copy after login

Server-Side Validation

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!