Home > Backend Development > PHP Tutorial > How to Restrict File Uploads to Specific Types in PHP?

How to Restrict File Uploads to Specific Types in PHP?

Mary-Kate Olsen
Release: 2024-11-11 17:32:02
Original
929 people have browsed it

How to Restrict File Uploads to Specific Types in PHP?

Restricting File Uploads to Specified Types in PHP

When creating a web page that allows users to upload files, it's essential to implement input validation to ensure that only permitted file types are uploaded to your server. In this context, you seek a solution to allow only specific file types (jpg, gif, and pdf) to be uploaded.

To achieve this, you can utilize an if statement combined with the in_array() function. First, retrieve the file's MIME type using $_FILES['foreign_character_upload']['type']. Then, define an array called $allowed containing the permitted MIME types for images (jpg, gif) and documents (pdf).

Using the in_array() function, check if the uploaded file's MIME type is in the $allowed array. If it's not found in the array, it means the file type is not allowed, and you can set the $error variable to indicate the error and display an error message. Here's an example code:

$file_type = $_FILES['foreign_character_upload']['type']; // Get file MIME type

$allowed = array("image/jpeg", "image/gif", "application/pdf"); // Allowed file types

if (!in_array($file_type, $allowed)) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}
Copy after login

The above is the detailed content of How to Restrict File Uploads to Specific Types 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