Home  >  Article  >  Backend Development  >  How to Validate File Size Before Upload: Client-Side vs. Server-Side?

How to Validate File Size Before Upload: Client-Side vs. Server-Side?

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 00:28:30987browse

How to Validate File Size Before Upload: Client-Side vs. Server-Side?

Checking File Size Before Upload

The given script efficiently verifies file type compliance. To additionally validate file size and prevent uploads exceeding 500kB, consider the following solutions:

Client-Side Canceling

Leverage the HTML5 File API to determine file size when the user selects a file:

<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 (this size is in bytes)
        //Submit form        
    } else {
        //Prevent default and display error
        evt.preventDefault();
    }
}, false);

Server-Side Canceling

Utilize the $_FILES array to retrieve the file size on the server:

<code class="php">if(isset($_FILES['file'])) {
    if($_FILES['file']['size'] > 10485760) { //10 MB (size is also in bytes)
        // File too big
    } else {
        // File within size restrictions
    }
}</code>

PHP ini Settings

If necessary, restrict uploads using the upload_max_filesize ini setting to a value suitable for all scenarios. Note that this is a global setting.

Significance of Client-Side Validation

Client-side validation provides a user-friendly experience by preventing unnecessary uploads and alerting the user to file issues. Server-side validation remains crucial for ensuring security, as client-side checks can be compromised.

The above is the detailed content of How to Validate File Size Before Upload: Client-Side vs. Server-Side?. 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