What security measures should be implemented when allowing users to upload files to a server in PHP?

When allowing users to upload files to a server in PHP, it is important to implement security measures to prevent malicious files from being uploaded. One key security measure is to validate the file type and size before allowing the upload. Additionally, it is important to store uploaded files in a secure directory outside of the web root to prevent direct access to the files.

// Validate file type and size
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
$maxSize = 5 * 1024 * 1024; // 5MB

if (in_array($_FILES['file']['type'], $allowedTypes) && $_FILES['file']['size'] <= $maxSize) {
    // Move uploaded file to secure directory
    move_uploaded_file($_FILES['file']['tmp_name'], '/path/to/secure/directory/' . $_FILES['file']['name']);
    echo 'File uploaded successfully!';
} else {
    echo 'Invalid file type or size!';
}