How to Validate Uploaded File Types in PHP with `in_array()`?

Mary-Kate Olsen
Release: 2024-11-12 13:46:02
Original
125 people have browsed it

How to Validate Uploaded File Types in PHP with `in_array()`?

Uploading Specified File Types with PHP

In web applications, allowing users to upload files requires careful consideration of security and content validation. When you want to restrict uploads to specific file types, PHP provides a solution through the in_array() function.

Problem:

You wish to create an if statement in PHP to validate uploaded files and allow only files of the following types: jpg, gif, and pdf. The code below requires the appropriate structuring of the if statement.

$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype

if(/*$file_type is anything other than jpg, gif, or pdf*/) {
  $error_message = 'Only jpg, gif, and pdf files are allowed.';
  $error = 'yes';
}
Copy after login

Solution:

To ensure files uploaded conform to your specifications, create an array of allowed file types and utilize in_array() to determine whether the uploaded file's mimetype is included in the array.

$file_type = $_FILES['foreign_character_upload']['type']; //returns the mimetype

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

By comparing the file type against the predefined list of allowed types, this revised if statement effectively prevents uploads of non-compliant files.

The above is the detailed content of How to Validate Uploaded File Types in PHP with `in_array()`?. 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