How can PHP developers prevent potential security risks when handling file uploads in forms?

When handling file uploads in forms, PHP developers should validate file types, limit file sizes, and store uploaded files in a secure directory outside the web root to prevent potential security risks such as file injection attacks. By implementing these measures, developers can ensure that only valid files are uploaded and stored securely.

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

// Limit file size
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds the limit of 2MB.');
}

// Store uploaded file in a secure directory
$uploadDir = '/path/to/secure/directory/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}