What security measures should be implemented when allowing users to upload files through PHP forms?

When allowing users to upload files through PHP forms, it is important to implement security measures to prevent malicious files from being uploaded and executed on the server. One key security measure is to validate file types and extensions to only allow specific file types to be uploaded. 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 extension
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
$uploadFile = $_FILES['file']['name'];
$ext = pathinfo($uploadFile, PATHINFO_EXTENSION);

if (!in_array($ext, $allowedExtensions)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and GIF files are allowed.');
}

// Store uploaded file in a secure directory
$targetDir = 'uploads/';
$targetFile = $targetDir . basename($_FILES['file']['name']);

if (!move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
    die('Failed to upload file.');
}