How can one properly validate user input in PHP when working with file uploads?
When working with file uploads in PHP, it is important to properly validate user input to prevent security vulnerabilities such as file injection attacks. One way to do this is by checking the file type and size before processing the upload. This can be done using PHP's built-in functions like `$_FILES['file']['type']` and `$_FILES['file']['size']`. Additionally, it's recommended to store uploaded files in a secure directory outside the web root to prevent direct access.
// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
die('Invalid file type. Allowed types are JPEG, PNG, GIF.');
}
// Validate file size
$maxSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxSize) {
die('File size is too large. Maximum size allowed is 1MB.');
}
// Move uploaded file to a secure directory
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo 'File uploaded successfully.';
} else {
echo 'Error uploading file.';
}