What are the best practices for storing uploaded files securely in PHP?

When storing uploaded files securely in PHP, it is important to validate the file type, sanitize the file name, store the files outside of the web root directory, and use a unique identifier for each file to prevent overwriting. Additionally, consider implementing access controls to restrict who can view or download the files.

// Validate file type
$allowedTypes = ['jpg', 'jpeg', 'png', 'pdf'];
$uploadedFileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploadedFileType, $allowedTypes)) {
    die('Invalid file type.');
}

// Sanitize file name
$fileName = preg_replace("/[^A-Za-z0-9.]/", '', $_FILES['file']['name']);

// Store file outside of web root directory
$uploadDir = '/var/www/uploads/';
$uploadPath = $uploadDir . $fileName;
move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);

// Generate unique identifier for file
$uniqueIdentifier = uniqid();
$newFileName = $uniqueIdentifier . '_' . $fileName;

// Implement access controls if needed
// For example, restrict access to files based on user roles or permissions