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

When allowing users to upload files in a PHP script, it is important to implement security measures to prevent malicious files from being uploaded. One common security measure is to restrict the file types that can be uploaded to only allow safe file types such as images or documents. Additionally, it is important to validate the file size to prevent large files from being uploaded and potentially causing performance issues or denial of service attacks.

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

// Check if the file size is within limits
$maxFileSize = 1048576; // 1MB
if ($_FILES['file']['size'] > $maxFileSize) {
    die('File size exceeds limit. Please upload a file smaller than 1MB.');
}

// Move the uploaded file to a secure location
$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.';
}