How can one validate file uploads in PHP to ensure security?
File uploads in PHP can pose security risks if not properly validated. To ensure security, one should check the file type, size, and content to prevent malicious files from being uploaded. Additionally, it is important to store uploaded files in a secure directory outside of the web root to prevent direct access.
<?php
$uploadDir = 'uploads/';
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1048576; // 1MB
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
if (in_array($fileType, $allowedTypes) && $fileSize <= $maxFileSize) {
$uploadPath = $uploadDir . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
echo 'File uploaded successfully.';
} else {
echo 'Invalid file type or size.';
}
} else {
echo 'Error uploading file.';
}
?>