What are best practices for storing uploaded files securely on a PHP server?

When storing uploaded files securely on a PHP server, it is important to validate file types, sanitize file names, store files outside of the web root directory, and use unique file names to prevent overwrite or access by unauthorized users.

// Example PHP code snippet for storing uploaded files securely
$uploadDir = '/path/to/upload/directory/';
$allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];

if(isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileType = $_FILES['file']['type'];
    
    if(in_array($fileType, $allowedTypes)) {
        $fileName = uniqid() . '_' . $_FILES['file']['name'];
        $uploadPath = $uploadDir . $fileName;
        
        if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
            echo 'File uploaded successfully.';
        } else {
            echo 'Failed to upload file.';
        }
    } else {
        echo 'Invalid file type.';
    }
} else {
    echo 'Error uploading file.';
}