Home >Backend Development >PHP Tutorial >How to Validate File Upload Types in PHP?

How to Validate File Upload Types in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-10 11:44:02420browse

How to Validate File Upload Types in PHP?

Uploading Specific File Formats in PHP with Conditional Validation

To limit file uploads to specific types, implement a conditional validation mechanism using the $_FILES global array and the in_array() function in PHP.

The code structure includes:

  1. Extract the file's mime type (mime): Obtain the file's mime type from the $_FILES'file' array. This value represents the file's format, such as "image/jpeg" for JPEG images.
  2. Define allowed file types (array): Create an array that contains the allowed file types' mime types. For example, if you want to allow only JPEG, GIF, and PDF files, your array could look like this:
$allowed = array('image/jpeg', 'image/gif', 'application/pdf');
  1. Compare to allowed types (if-statement): Use the in_array() function to compare the file's mime type with the allowed types. This function returns 'true' if the mime type matches any entry in the $allowed array, and 'false' otherwise. Wrap this condition in an if-statement to check if the file type is not allowed.

Here's the modified code:

$mime = $_FILES['foreign_character_upload']['type']; // File mime type

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

If the file's mime type does not match any of the allowed types, the if-condition will be true and the $error and $error_message variables will be set accordingly. This enables you to handle the upload error and provide feedback to the user.

The above is the detailed content of How to Validate File Upload Types 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