Home >Backend Development >PHP Tutorial >How to Validate Uploaded Filetypes to Ensure Security in PHP?
Determining Allowed Filetypes for Upload using PHP
Maintaining security and controlling the types of files uploaded to a website is crucial. PHP offers various methods to validate and restrict file uploads based on specific criteria. One common scenario is limiting uploads to specific filetypes, such as images and documents.
Limiting Filetypes to JPG, GIF, and PDF
Consider a scenario where a form allows users to upload files, but only JPG, GIF, and PDF formats are permitted. A concise PHP code snippet to achieve this is:
<?php $file_type = $_FILES['foreign_character_upload']['type']; // Get the file type $allowed = array("image/jpeg", "image/gif", "application/pdf"); // Allowed file types in an array if(!in_array($file_type, $allowed)) { $error_message = 'Only jpg, gif, and pdf files are allowed.'; $error = 'yes'; } ?>
In this code, we:
The above is the detailed content of How to Validate Uploaded Filetypes to Ensure Security in PHP?. For more information, please follow other related articles on the PHP Chinese website!