Home > Database > Mysql Tutorial > How to Securely Restrict File Types in PHP File Uploads?

How to Securely Restrict File Types in PHP File Uploads?

DDD
Release: 2024-11-03 03:13:02
Original
489 people have browsed it

How to Securely Restrict File Types in PHP File Uploads?

PHP File Upload: Restricting File Types

When handling file uploads, it's crucial to validate the uploaded file's type and size to ensure security and maintain intended functionality. The provided code aims to do so by checking the file extension, type, and size. However, it has some issues.

Issues with the Original Code:

  • Doesn't enforce the file type; it allows files with unauthorized extensions (e.g., TXT).
  • Doesn't check the file size correctly.

Solution:

To address these issues, we can utilize the mime types for file validation and separate checks for the size limit.

Updated Code:

<code class="php">function allowed_file() {
  // Allowed mime types
  $allowed = array('application/doc', 'application/pdf', 'another/type');

  // Validate file type using mime type
  if (in_array($_FILES['resume']['type'], $allowed) && in_array($_FILES['reference']['type'], $allowed)) {

    // Validate file size
    if ($_FILES["resume"]["size"] < 400000 && $_FILES["reference"]["size"] < 400000) {

      // Files are allowed; proceed with upload process...
    }
  }
}</code>
Copy after login

Explanation:

  • We define an array of allowed mime types.
  • For each uploaded file, we check if its mime type is in the allowed array.
  • After validating the file types, we perform size checks to ensure they're below the specified limit.
  • If all validations pass, we can proceed with the file upload process, such as moving to the desired destination.

The above is the detailed content of How to Securely Restrict File Types in PHP File Uploads?. 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