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'; }
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'; }
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!