Home >Backend Development >PHP Tutorial >How Can You Validate File Size Before Uploading?

How Can You Validate File Size Before Uploading?

DDD
DDDOriginal
2024-10-26 10:14:02952browse

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>

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>

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!

Statement:
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