How can security vulnerabilities be addressed when allowing file uploads in PHP forms?

Security vulnerabilities when allowing file uploads in PHP forms can be addressed by validating the file type, restricting the file size, and storing the uploaded files in a secure location outside the web root directory. Additionally, using functions like move_uploaded_file() and checking for errors during the upload process can help prevent malicious file uploads.

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png'];
if (!in_array($_FILES['file']['type'], $allowedTypes)) {
    die('Invalid file type. Only JPEG and PNG files are allowed.');
}

// Restrict file size
$maxFileSize = 1000000; // 1MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size is too large. Maximum file size allowed is 1MB.');
}

// Store uploaded file in a secure location
$uploadDir = '/var/www/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.';
}