What security measures should be considered when handling file uploads in PHP?

When handling file uploads in PHP, it is important to implement security measures to prevent malicious files from being uploaded to the server. Some key security measures to consider include checking the file type, limiting the file size, and storing the files outside of the web root directory to prevent direct access.

// Check 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.');
}

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

// Store file outside of web root directory
$targetDir = '/path/to/uploads/';
$targetFile = $targetDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}