What are the best practices for securely managing user-uploaded files in PHP applications, especially when considering potential security vulnerabilities?

When managing user-uploaded files in PHP applications, it is crucial to implement security measures to prevent potential vulnerabilities such as file inclusion attacks, malicious file uploads, and directory traversal exploits. To securely manage user-uploaded files, it is recommended to validate file types, store files outside the web root directory, restrict file permissions, and sanitize file names before processing them.

// Example of securely managing user-uploaded files in PHP

// Define the directory where uploaded files will be stored
$uploadDirectory = '/path/to/uploaded/files/';

// Validate file type before processing
$allowedFileTypes = ['jpg', 'jpeg', 'png', 'pdf'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileType, $allowedFileTypes)) {
    die('Invalid file type. Only JPG, JPEG, PNG, and PDF files are allowed.');
}

// Move the uploaded file to the designated directory
$uploadedFilePath = $uploadDirectory . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadedFilePath)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Failed to upload file.';
}

// Sanitize file name to prevent directory traversal exploits
$cleanFileName = preg_replace('/[^A-Za-z0-9_\-\.]/', '', $_FILES['file']['name']);