How can PHP developers restrict file uploads to specific file extensions for security purposes?
To restrict file uploads to specific file extensions for security purposes, PHP developers can validate the file extension before allowing the upload. This helps prevent users from uploading potentially harmful files like executable scripts. By checking the file extension against a predefined list of allowed extensions, developers can ensure that only safe file types are accepted.
// Define an array of allowed file extensions
$allowedExtensions = array('jpg', 'png', 'pdf');
// Get the uploaded file's extension
$uploadedFileExtension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
// Check if the uploaded file's extension is in the list of allowed extensions
if (!in_array($uploadedFileExtension, $allowedExtensions)) {
echo 'Invalid file type. Only JPG, PNG, and PDF files are allowed.';
exit;
}
// Continue with the file upload process