Introduction:
In web applications, it's often necessary to limit the size of files uploaded by users. This helps prevent abuse, conserve storage space, and ensure efficient processing.
Client-Side Validation:
Modern browsers support the HTML5 File API, which allows you to check the file size client-side.
<br><script><br>document.forms[0].addEventListener('submit', function(evt) {</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">var file = document.getElementById('file').files[0]; if (file && file.size < 10485760) { // 10 MB (in bytes) // Submit form } else { // Prevent submission and display error evt.preventDefault(); }
}, false);
Server-Side Validation:
On the server side, use PHP to verify the file size:
<br><?php<br>if (isset($_FILES['file'])) {</p><div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">if ($_FILES['file']['size'] > 10485760) { // 10 MB (in bytes) // File too large } else { // File within size restrictions }</p>
}
?php>
Additional Considerations:
The above is the detailed content of How to Ensure Files Don't Exceed Size Limits During Web Uploads?. For more information, please follow other related articles on the PHP Chinese website!