Home >Database >Mysql Tutorial >How to Restrict File Upload Types and Sizes in PHP?

How to Restrict File Upload Types and Sizes in PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 01:14:02946browse

How to Restrict File Upload Types and Sizes in PHP?

Restricting File Upload Types in PHP

When handling file uploads, it's crucial to validate file types and sizes to prevent unauthorized or malicious content from being uploaded to your system. In your case, you're experiencing issues with the current code, which isn't restricting file types correctly and isn't checking file sizes.

To solve this, let's use a more reliable approach:

<code class="php">function allowed_file() {
  // Create an array of allowed mime types
  $allowed = array('application/doc', 'application/pdf', 'application/docx');

  // Check if both files are allowed types
  if (in_array($_FILES['resume']['type'], $allowed) && in_array($_FILES['reference']['type'], $allowed)) {
    // Check file sizes
    if ($_FILES["resume"]["size"] < 400000 && $_FILES["reference"]["size"] < 400000) {
      // File types and sizes are both valid
      return true;
    }
  }

  // Otherwise, return false
  return false;
}</code>

Explanation:

  • We create an array of allowed mime types that includes the desired types (pdf, doc, docx).
  • We use in_array() to check if both files' mime types are present in the allowed array.
  • If file types are allowed, we check both files' sizes to ensure they're below the specified limit.
  • If all conditions are met, the function returns true, allowing file upload. Otherwise, it returns false.

By using mime types to validate file types and explicitly checking file sizes, you can effectively restrict file uploads and ensure only authorized and non-malicious files are uploaded to your system.

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