Home > Article > Backend Development > How to Restrict File Uploads to Specific 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'; }
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!