Home > Database > Mysql Tutorial > body text

How to Restrict File Upload Types and Size in PHP?

Susan Sarandon
Release: 2024-11-01 02:14:02
Original
776 people have browsed it

How to Restrict File Upload Types and Size in PHP?

Restricting File Upload Types in PHP

You're facing issues with restricting file upload types to PDF, DOC, or DOCX and limiting file size to less than 400 KB. Your provided code attempts to validate file extensions and sizes; however, it has some flaws.

To resolve these issues, you can use the following code:

<code class="php">function allowed_file() {
    // Define allowed MIME types
    $allowed_types = array('application/doc', 'application/docx', 'application/pdf');

    // Validate uploaded files
    if (in_array($_FILES['resume']['type'], $allowed_types) && in_array($_FILES['reference']['type'], $allowed_types)) {
        // Check file sizes
        if ($_FILES["resume"]["size"] < 400000 && $_FILES["reference"]["size"] < 400000) {
            // Files allowed for upload
        } else {
            // File size exceeded limit
        }
    } else {
        // Invalid file type
    }
}</code>
Copy after login

Explanation:

  • This code uses an array of allowed MIME types to validate the file types.
  • It checks if the MIME types of both 'resume' and 'reference' files match an allowed type.
  • If the file types are valid, it proceeds to check if their sizes are within the limit (less than 400 KB).
  • Depending on the validation results, you can handle the file upload accordingly.

The above is the detailed content of How to Restrict File Upload Types and Size in PHP?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template